Collectives™ on Stack Overflow
Find centralized, trusted content and collaborate around the technologies you use most.
Learn more about Collectives
Teams
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
Learn more about Teams
I'm implementing a method
Task<Result> StartSomeTask()
and happen to know the result already before the method is called. How do I create a
Task<T>
that has already completed?
This is what I'm currently doing:
private readonly Result theResult = new Result();
public override Task<Result> StartSomeTask()
var task = new Task<Result>(() => theResult);
task.RunSynchronously(CurrentThreadTaskScheduler.CurrentThread);
return task;
Is there a better solution?
–
–
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; }
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;
–
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.