开始和等待有什么区别?下面的代码取自 Stephen Cleary 的博客(包括评论)
public async Task DoOperationsConcurrentlyAsync()
{
Task[] tasks = new Task[3];
tasks[0] = DoOperation0Async();
tasks[1] = DoOperation1Async();
tasks[2] = DoOperation2Async();
// At this point, all three tasks are running at the same time.
// Now, we await them all.
await Task.WhenAll(tasks);
}
Run Code Online (Sandbox Code Playgroud)
我认为任务在您等待它们时开始运行......但代码中的注释似乎暗示不然。另外,在我将任务归因于类型为 Task 的数组后,这些任务如何运行。这难道不是一种归因,本质上不涉及行动吗?
如何重写TaskOfTResult_MethodAsync
以避免错误:由于这是一个异步方法,返回表达式必须是类型int
而不是Task<int>
.
private static async Task<int> TaskOfTResult_MethodAsync()
{
return Task.Run(() => ComplexCalculation());
}
private static int ComplexCalculation()
{
double x = 2;
for (int i = 1; i< 10000000; i++)
{
x += Math.Sqrt(x) / i;
}
return (int)x;
}
Run Code Online (Sandbox Code Playgroud)