foreach中的异步方法并将结果添加到列表中

时间:2019-05-28 11:03:12

标签: c# wpf foreach async-await

我想在foreach中运行asyncron的几种方法。返回值应写入列表。

该方法在WPF应用程序中执行。方法GetItemPricesFromJsonAsync从网络数据中获取。

public async Task LoadBlackMarketListView(List<MarketAnalysisManager.ItemTier> tiers, List<MarketAnalysisManager.ItemLevel> levels, 
            List<MarketAnalysisManager.ItemQuality> quialityList, string outdatedHours, string profit, Location? location)
        {
            await Task.Run(async () =>
            {
                var blackMarketSellObjectList = new List<BlackMarketSellObject>();

                var items = await MarketAnalysisManager.GetItemListAsync(tiers, levels);

                await Dispatcher.InvokeAsync(() =>
                {
                    PbBlackMarketMode.Minimum = 0;
                    PbBlackMarketMode.Maximum = items.Count;
                    PbBlackMarketMode.Value = 0;
                    GridBlackMarketMode.IsEnabled = false;
                    LvBlackMarket.Visibility = Visibility.Hidden;
                    PbBlackMarketMode.Visibility = Visibility.Visible;
                });

                foreach (var item in items)
                {
                    var allItemPrices = await MarketAnalysisManager.GetItemPricesFromJsonAsync(item.UniqueName, true);
                    if (allItemPrices.FindAll(a => a.City == Locations.GetName(Location.BlackMarket)).Count <= 0)
                    {
                        await IncreaseBlackMarketProgressBar();
                        continue;
                    }

                    blackMarketSellObjectList.AddRange(await GetBlackMarketSellObjectList(item, quialityList, allItemPrices, outdatedHours, profit, location));

                    await IncreaseBlackMarketProgressBar();
                }

                await Dispatcher.InvokeAsync(() =>
                {
                    LvBlackMarket.ItemsSource = blackMarketSellObjectList;
                    PbBlackMarketMode.Visibility = Visibility.Hidden;
                    LvBlackMarket.Visibility = Visibility.Visible;
                    GridBlackMarketMode.IsEnabled = true;
                });
            });

        }

目前看来他一次只做一件事。

运行... 0

结束... 0

运行... 1

结束... 1

运行... 2

结束... 2

1 个答案:

答案 0 :(得分:3)

您将需要存储任务,而不要等待它们。然后,您可以等待所有这些人。
试试看(用我的代码替换您的foreach)。
我还建议您使用一种真实的方法来代替匿名方法,因为它更易读。


.content-container {
    margin: 0 auto;
    padding: 0;
    display: flex;
    flex-direction: row; 
    width: 90%;
    padding-top: 20px;

    .col-nav {
      position: absolute;
      top: $toolbarHeight + 5px;
      left: 0;
    }

    .col-products {
      flex: 12;
    }
  }

注意:因为这是一个匿名函数,所以现在返回而不是继续,您只需要在此结束该函数而不是继续使用foreach。