Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create a completed Task<T>

People also ask

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 create a new task in C#?

To start a task in C#, follow any of the below given ways. Use a delegate to start a task. Task t = new Task(delegate { PrintMessage(); }); t. Start();

What is task Completedtask?

This property returns a task whose Status property is set to RanToCompletion. To create a task that returns a value and runs to completion, call the FromResult method. Repeated attempts to retrieve this property value may not always return the same instance.

How do I return a null in task?

We can return null from a method that returns a Task because Task is a reference type. In our previous example, we return null from NonAsyncFoo() . But, awaiting null isn't legal, so await NonAsyncFoo() throws a NullReferenceException .


When targeting .NET 4.5 you can use Task.FromResult:

public static Task<TResult> FromResult<TResult>(TResult result);

To create a failed task, use Task.FromException:

public static Task FromException(Exception exception);
public static Task<TResult> FromException<TResult>(Exception exception);

.NET 4.6 adds Task.CompletedTask if you need a non generic Task.

public static Task CompletedTask { get; }

Workarounds for older versions of .NET:

  • When targeting .NET 4.0 with Async Targetting Pack (or AsyncCTP) you can use TaskEx.FromResult instead.

  • To get non-generic Task prior to .NET 4.6, you can use the fact that Task<T> derives from Task and just call Task.FromResult<object>(null) or Task.FromResult(0).


private readonly Result theResult = new Result();

public override Task<Result> StartSomeTask()
{
    var taskSource = new TaskCompletionSource<Result>();
    taskSource.SetResult(theResult);
    return taskSource.Task;
}

For tasks with no return value, .NET 4.6 has added Task.CompletedTask.

It returns a task which is already in TaskStatus.RanToCompletion. It probably returns the same instance every time, but the documentation warns you not to count on that fact.


If you're using Rx, an alternative is Observable.Return(result).ToTask().


Calling Task.WhenAll without any parameters will return a completed task.

Task task = Task.WhenAll();