我有这个简单的代码,可以异步启动方法。它使用TCS
以便使用Task包装代码。
Task<int> DoWork()
{
var source = new TaskCompletionSource <int>();
Thread.Sleep(220);
source.SetResult(9999999);
return source.Task;
}
void Main()
{
Console.WriteLine(1);
var t1=Task.Factory.StartNew(()=>DoWork());
t1.ContinueWith(_=>Console.WriteLine ("doing something different "));
t1.ContinueWith(_=>Console.WriteLine ("finished , value is ="+_.Result.Result));
Console.WriteLine(2);
Console.ReadLine();
}
输出 :
1
2
doing somethign different //those last 2 lines can be swapped
finished , value is =9999999
但是现在,我想将其转换为使用
Task.FromResult<TResult>
。这是poorly documented,所以我想知道如何将上面的代码转换为使用
Task.FroResult
?
最佳答案
使用FromResult
的最简单方法是:
public Task<int> DoWork()
{
return Task.FromResult(99999);
}
但这与执行功能完全相同:
var tcs = new TaskCompletionSource<int>();
tcs.SetResult(99999);
return tcs.Task;
因此它不会休眠220毫秒。对于“延迟”变体,最简单的方法是:
public async Task<int> DoWork()
{
await Task.Delay(220);
return 99999;
}
并且此版本的行为与您提供的示例足够接近。
关于c# - 将TaskCompletionSource转换为Task.FromResult <TResult>吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17338873/