Parallel.ForEach中的多个异步等待链接

问题描述 投票:1回答:1

我有一个Parallel.ForEach循环,该循环遍历一个集合。在内部,循环进行多个网络I / O调用。我使用Task.ContinueWith并嵌套了后续的async-await调用。处理的顺序无关紧要,但是每个异步调用中的数据都应该以同步方式进行处理。含义-对于每个迭代,应该将从第一个异步调用中检索到的数据传递给第二个异步调用。在第二个异步调用完成之后,两个异步调用中的数据应一起处理。

Parallel.ForEach(someCollection, parallelOptions, async (item, state) =>
{
    Task<Country> countryTask = Task.Run(() => GetCountry(item.ID));

    //this is my first async call
    await countryTask.ContinueWith((countryData) =>
    {
        countries.Add(countryData.Result);

        Task<State> stateTask = Task.Run(() => GetState(countryData.Result.CountryID));

        //based on the data I receive in 'stateTask', I make another async call
        stateTask.ContinueWith((stateData) =>
        {
            states.Add(stateData.Result);

            // use data from both the async calls pass it to below function for some calculation
            // in a synchronized way (for a country, its corresponding state should be passed)

            myCollection.ConcurrentAddRange(SomeCalculation(countryData.Result, stateData.Result));
        });
    });
});

我尝试了以上方法,但没有使用continue等待,但是它不能以同步方式工作。现在,以上代码执行完毕,但未处理任何记录。

对此有任何帮助吗?让我知道是否可以添加更多详细信息。

c# asynchronous async-await task-parallel-library parallel.foreach
1个回答
© www.soinside.com 2019 - 2024. All rights reserved.