【发布时间】:2013-11-14 12:02:01
【问题描述】:
我从这里http://blog.stephencleary.com/2012/02/async-and-await.html阅读了这个指南
这里我有几个代码,但对我来说不是很清楚。
1)
public async Task DoOperationsInParallelAsync()
{
Task[] tasks = new Task[3];
tasks[0] = DoOperation0();
tasks[1] = DoOperation1();
tasks[2] = DoOperation2();
// At this point, all three tasks are running in parallel.
// Now, we await them all.
await Task.WhenAll(tasks);
}
在上面我们创建了多个任务,但假设当所有任务将并行运行时,DoOperation2() 可能首先完成,DoOperation0() 和最后 DoOperation1() 完成。如果我想在控制台窗口中显示像 DoOperation2() 这样的消息,那么我该怎么做。当多个正在运行时,我如何检测哪个任务完成。
2) 当我们在 async/await 的帮助下运行任何函数时,它是作为后台线程还是前台线程运行。
3)
public async Task<int> GetFirstToRespondAsync()
{
// Call two web services; take the first response.
Task<int>[] tasks = new[] { WebService1(), WebService2() };
// Await for the first one to respond.
Task<int> firstTask = await Task.WhenAny(tasks);
// Return the result.
return await firstTask;
}
我不明白这个人为什么写等待第一个回复。
// 等待第一个响应。 Task firstTask = await Task.WhenAny(tasks);
为什么是第一个...为什么不是第二个,因为这里正在运行两个任务。
请指导我并消除我的困惑。谢谢
【问题讨论】:
-
我认为您的一些困惑是由语言引起的:第一个响应并不意味着第一个条目,而是意味着先响应的将是第一个。
标签: c# asynchronous