开发者

Correct way to create a task with a result already ready

开发者 https://www.devze.com 2023-04-06 01:13 出处:网络
Sometimes I create a method like this Task<int> f() { if (...) return Task.Factory.StartNew(() => 42); // in this case, result already known

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

精彩评论

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

关注公众号