Correct way to create a task with a result already ready
Sometimes I create a method like this
Task<int> f()
{
if (...) return Task.Factory.StartNew(() => 42); // in this case, result already known
else ... // return some "real task"
}
But I was wondering if there is a way to create a task thas is already completed, so that I won't incur any p开发者_如何学JAVAotential overhead of scheduling the "calculation" 42
Use TaskCompletionSource<T>
:
TaskCompletionSource<int> tcs = new TaskCompletionSource<int>();
tcs.SetResult(42);
return tcs.Task;
(via MSDN)
精彩评论