I want to create a completed Task
(not Task<T>
). Is there something built into .NET to do this?
A related question: Create a completed Task<T>
Task Completion definition: it is a specific condition of a task, which matches certain “completion” criteria that is a special set of characteristics to recognize that a task was successfully accomplished.
Mark as Complete When you finish a task, you can check it off your Tasks list by marking it as complete. Completing a task will hide it from the To-Do list, or any other Task view that only displays active tasks.
NotifyCompleted() , so we could create a Task in one place, and mark it as completed in another place – all this was working asynchronously.
Show completed tasks in the Tasks viewIn Tasks, on the View tab, in the Current View group, click Change View and then click Completed.
The newest version of .Net (v4.6) is adding just that, a built-in Task.CompletedTask:
Task completedTask = Task.CompletedTask;
That property is implemented as a no-lock singleton so you would almost always be using the same completed task.
Task<T>
is implicitly convertable to Task
, so just get a completed Task<T>
(with any T
and any value) and use that. You can use something like this to hide the fact that an actual result is there, somewhere.
private static Task completedTask = Task.FromResult(false); public static Task CompletedTask() { return completedTask; }
Note that since we aren't exposing the result, and the task is always completed, we can cache a single task and reuse it.
If you're using .NET 4.0 and don't have FromResult
then you can create your own using TaskCompletionSource
:
public static Task<T> FromResult<T>(T value) { var tcs = new TaskCompletionSource<T>(); tcs.SetResult(value); return tcs.Task; }
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