In unit testing a component I need to verify how a component reacts to Tasks being completed at various times.
How do I create a Task<>
that I can resolve at will?
You can use a TaskCompletionSource to create a fully 'manual' task. Represents the producer side of a Task unbound to a delegate, providing access to the consumer side through the Task property. Hand out the the completion source's Task property to the consumer, and call SetResult on it (at will) to complete the task.
NET framework provides Threading. Tasks class to let you create tasks and run them asynchronously. A task is an object that represents some work that should be done. The task can tell you if the work is completed and if the operation returns a result, the task gives you the result.
This method is useful when you perform an asynchronous operation that returns a Task object, and the result of that Task object is already computed. Show activity on this post. Use the Task. FromResult when you want to have a asynchronous operation but sometimes the result is in hand synchronously.
You can use a TaskCompletionSource
to create a fully 'manual' task.
Represents the producer side of a Task unbound to a delegate, providing access to the consumer side through the Task property.
Hand out the the completion source's Task
property to the consumer, and call SetResult
on it (at will) to complete the task. Note that you also have SetCanceled
and SetException
to represent cancellations and failures, respectively.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With