我正在尝试使用Task.WhenAll
来等待多个任务的完成。
我的代码如下 - 它应该启动多个异步任务,每个任务都会检索一条公交路线,然后将它们添加到本地数组中。但是,Task.WhenAll(...)
立即返回,并且本地路由数组的计数为零。这似乎很奇怪,因为我希望每个语句中的各种await
语句都Task
意味着流被暂停,并且Task
直到它完成才返回。
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());
我显然做错了什么-但是什么?