Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create a completed Task

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>

like image 223
Timothy Shields Avatar asked Jan 09 '13 18:01

Timothy Shields


People also ask

What is a completed task?

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.

What happens to a task when you mark it as complete?

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.

How do you mark a task completed in C#?

NotifyCompleted() , so we could create a Task in one place, and mark it as completed in another place – all this was working asynchronously.

How do I view completed tasks?

Show completed tasks in the Tasks viewIn Tasks, on the View tab, in the Current View group, click Change View and then click Completed.


2 Answers

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.

like image 59
i3arnon Avatar answered Sep 22 '22 20:09

i3arnon


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; } 
like image 28
Servy Avatar answered Sep 23 '22 20:09

Servy