我对C#中的停止Parallel.ForEachAsync
循环感兴趣(考虑到Stop
和Break
之间的区别);对于Parallel.ForEach
,我可以进行以下操作:
Parallel.ForEach(items, (item, state) =>
{
if (cancellationToken.IsCancellationRequested)
{
state.Stop();
return;
}
// some process on the item
Process(item);
});
然而,由于我有一个需要异步执行的进程,我转而使用
Parallel.ForEachAsync
。 ForEachAsync
没有Stop()
方法,我可以像下面这样使用break
来中断循环,但我想知道这是否是最有效的中断循环的方法(换句话说,当收到取消请求时,循环需要尽快停止)。await Parallel.ForEachAsync(items, async (item, state) =>
{
if (cancellationToken.IsCancellationRequested)
{
return;
}
// some async process on the item
await ProcessAsync(item);
});