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.FromResultinstead. -
To get non-generic
Taskprior to .NET 4.6, you can use the fact thatTask<T>derives fromTaskand just callTask.FromResult<object>(null)orTask.FromResult(0).