9

我正在尝试使用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());

我显然做错了什么-但是什么?

4

2 回答 2

8

这归结为对 async-await 的真正工作原理缺乏基本了解。

内部任务将流程返回到外部任务,然后在等待返回之前完成。

为了实现我想要的,我需要重构如下:

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
}

感谢戴夫·斯密茨

于 2012-08-14T11:01:52.290 回答
6

我怀疑问题出在您对Task.Factory.StartNew(). 我怀疑您最终会得到 a Task<Task>,而您只会发现它何时有效地启动了任务。

试试这个:

Func<Task> taskFunc = 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);
    });

}

Task getRouteTask = Task.Run(taskFunc);
于 2012-08-14T11:00:26.150 回答