Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a Task<> I can complete manually

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?

like image 886
George Mauer Avatar asked Jan 11 '15 19:01

George Mauer


People also ask

How do you complete a Task in C#?

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.

How are tasks created in .NET framework?

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.

Should I use Task FromResult?

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.


1 Answers

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.

like image 73
Ani Avatar answered Oct 09 '22 21:10

Ani