Coder Perfect

Complete the task.


I’d like to make a finished Task (not TaskT>). Is there something in.NET that can achieve this?

Create a completed TaskT>, which is a related question.

Asked by Timothy Shields

Solution #1

The most recent version of.Net (v4.6) includes a built-in Task. CompletedTask:

Task completedTask = Task.CompletedTask;

Because that property is a no-lock singleton, you’ll virtually always be using the same completed job.

Answered by i3arnon

Solution #2

Because TaskT> is inherently convertable to Task, all you have to do is get a finished TaskT> (with any T and value) and utilize it. Something like this can be used to hide the fact that a real result exists someplace.

private static Task completedTask = Task.FromResult(false);
public static Task CompletedTask()
    return completedTask;

We can cache and reuse a single job because we aren’t presenting the result and the task is always completed.

You can create your own TaskCompletionSource: if you’re using.NET 4.0 and don’t have FromResult.

public static Task<T> FromResult<T>(T value)
    var tcs = new TaskCompletionSource<T>();
    return tcs.Task;

Answered by Servy

Solution #3

Task is my preferred approach for accomplishing this. WhenAll() is a function that takes no arguments. “If the supplied array/enumerable includes no tasks, the returned task will instantly transition to a RanToCompletion state before it’s returned to the caller,” according to the MSDN documentation. That sounds like exactly what you’re looking for.

Update: I discovered the source at Microsoft’s Reference Source, where the Task may be located. The following is found in WhenAll:

return (tasks.Length == 0) ? // take shortcut if there are no tasks upon which to wait
            Task.CompletedTask :
            new WhenAllPromise(tasks);

So, here’s the job. Although CompletedTask is internal, it can be accessed by executing WhenAll() without any arguments.

Answered by Richiban

Solution #4

Task.Delay would be my choice (0). Internally, it returns a cached instance of a TaskT> that has been completed. This is exactly what the current solution suggests, except now you don’t have to cache an instance yourself, and your code isn’t littered with inelegant garbage values.

You may believe that Task will suffice. Yield() is used instead, but the outcome is Task. Task is not a subtype of Yield(), but Yield() is a result of Task. It’s Delay(0). One of the minor distinctions between the two is this.

Answered by gzak

Solution #5

You can use Task.FromResult (in .NET 4.5) to return a completed Task.

You can always use Task if you require a non-generic Task. Because TaskT> is a subclass of Task, use FromResult(0) or something like.

Answered by Reed Copsey

Post is based on