问题描述
我想使用Task.WhenAll等待多个任务的完成。
I am trying to use Task.WhenAll to await completion of multiple tasks.
我code是低于 - 它应该启动多个异步任务,每个检索公共汽车路线,然后将它们添加到一个本地阵列。然而,Task.WhenAll(...)立即返回,并且本地路由阵列的计数是零。这似乎很奇怪,因为我期望的各种'等待'每个任务中的语句,意味着流被暂停,并且任务不返回,直到它完成。
My code is below - it is supposed to launch multiple async tasks, each of which retrieves a bus route and then adds them to a local array. However, Task.WhenAll(...) returns immediately, and the count of the local routes array is zero. This seems strange, since I would expect the various 'await' statements within each Task to mean that the flow is suspended, and the Task does not return until it's finished.
List<Task> monitoredTasks = new List<Task>();
foreach (BusRouteIdentifier bri in stop.services)
{
BusRouteRequest req = new BusRouteRequest(bri.id);
// Start a new task to fetch the route for each stop
Task getRouteTask = Task.Factory.StartNew(async () =>
{
var route = await BusDataProviderManager.DataProvider.DataBroker.getRoute(req);
// Add the route to our array (on UI thread as it's observed)
await dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, delegate
{
this.routes.Add(route);
});
});
// Store the task in our monitoring list
monitoredTasks .Add(getRouteTask);
}
Debug.WriteLine("Awaiting WHENALL");
await Task.WhenAll(monitoredTasks );
Debug.WriteLine(string.Format("WHENALL returned (routes count is {0} ", this.routes.Count));
this.OnWillEndFetchingRoutes(new EventArgs());
我明明做错了 - 但什么
I'm obviously doing something wrong - but what?
推荐答案
这是下降到一个基本的缺乏如何异步伺机真正起作用的理解。
This was down to a basic lack of understanding of how async-await really works.
内任务返回流动到外任务时,伺机以往任何时候都返回之前,然后结束了。
The inner task was returning flow to the outer task, which then finished before the await ever returned.
要实现我想要的东西,我需要重构如下:
To achieve what I wanted, I needed to refactor as follows:
List<Task<BusRoute>> routeRetrievalTasks = new List<Task<BusRoute>>();
foreach (BusRouteIdentifier bri in stop.services)
{
BusRouteRequest req = new BusRouteRequest(bri.id);
routeRetrievalTasks.Add(BusDataProviderManager.DataProvider.DataBroker.getRoute(req));
}
foreach (var task in routeRetrievalTasks)
{
var route = await task;
this.routes.Add(route); // triggers events
}
感谢Dave史密茨
这篇关于如何正确使用Task.WhenAll()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!