开发者

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)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜