c# - Parallel.ForEach 中的多个异步等待链接
问题描述
我有一个 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 await 的情况下尝试了上述方法,但它没有以同步方式工作。现在,上面的代码执行完成,但没有记录被处理。
请问有什么帮助吗?让我知道是否可以添加更多详细信息。
解决方案
由于您的方法涉及 I/O,因此它们应该被编写为真正异步的,而不仅仅是使用Task.Run
.
然后你可以Task.WhenAll
结合使用Enumerable.Select
:
var tasks = someCollection.Select(async item =>
{
var country = await GetCountryAsync(item.Id);
var state = await GetStateAsync(country.CountryID);
var calculation = SomeCalculation(country, state);
return (country, state, calculation);
});
foreach (var tuple in await Task.WhenAll(tasks))
{
countries.Add(tuple.country);
states.Add(tuple.state);
myCollection.AddRange(tuple.calculation);
}
这将确保每个country
> state
>calculation
顺序发生,但每个item
都是同时和异步处理的。
根据评论更新
using var semaphore = new SemaphoreSlim(2);
using var cts = new CancellationTokenSource();
int failures = 0;
var tasks = someCollection.Select(async item =>
{
await semaphore.WaitAsync(cts.Token);
try
{
var country = await GetCountryAsync(item.Id);
var state = await GetStateAsync(country.CountryID);
var calculation = SomeCalculation(country, state);
Interlocked.Exchange(ref failures, 0);
return (country, state, calculation);
{
catch
{
if (Interlocked.Increment(ref failures) >= 10)
{
cts.Cancel();
}
throw;
}
finally
{
semaphore.Release();
}
});
信号量保证最多 2 个并发异步操作,取消令牌将在连续 10 次异常后取消所有未完成的任务。
这些Interlocked
方法确保failures
以线程安全的方式访问。
进一步更新
使用 2 个信号量来防止多次迭代可能更有效。
将所有列表添加封装到一个方法中:
void AddToLists(Country country, State state, Calculation calculation)
{
countries.Add(country);
states.Add(state);
myCollection.AddRange(calculation);
}
然后,您可以允许 2 个线程同时处理 Http 请求,并允许 1 个线程执行添加,从而使该操作线程安全:
using var httpSemaphore = new SemaphoreSlim(2);
using var listAddSemaphore = new SemaphoreSlim(1);
using var cts = new CancellationTokenSource();
int failures = 0;
await Task.WhenAll(someCollection.Select(async item =>
{
await httpSemaphore.WaitAsync(cts.Token);
try
{
var country = await GetCountryAsync(item.Id);
var state = await GetStateAsync(country.CountryID);
var calculation = SomeCalculation(country, state);
await listAddSemaphore.WaitAsync(cts.Token);
AddToLists(country, state, calculation);
Interlocked.Exchange(ref failures, 0);
{
catch
{
if (Interlocked.Increment(ref failures) >= 10)
{
cts.Cancel();
}
throw;
}
finally
{
httpSemaphore.Release();
listAddSemaphore.Release();
}
}));
推荐阅读
- node.js - 每当我尝试使用 Powershell 安装 Firebase CLI 时都会收到此错误
- google-sheets - 如何使用具有重复值的 INDEX(MATCH())
- c++ - 在 Visual Studio 2019 中使用 boost::object_pool boost 版本 1.56 时出现问题
- mysql - 如何在此表上使用自连接,而不是在发生连接时使用子查询?
- javascript - 错误:函数超时,确保承诺在内部解决 - Cucumber js
- node.js - Ubuntu 用户无法打开端口来监听 IP V6 地址
- javascript - (奇怪的)JavaScript 执行顺序
- javascript - 使用带有 JavaScript / Fetch 的 SpreadShirt REST API
- javascript - findByIdAndUpdate 从等于特定值的数组对象中提取
- powershell - PowerShell - 如何停止脚本处理 Timer 类中的已用事件