我想在C#中异步并行执行for循环。但Parallel类只包含一个同步For方法和一个异步ForEachAsync方法(.NET 6)。这对我来说似乎是一个疏忽。Parallel.ForAsync方法在哪里?有什么解决方法吗?
Parallel
For
ForEachAsync
Parallel.ForAsync
gwo2fgha1#
我同意没有Parallel.ForAsync方法看起来是一个巨大的疏忽。不过我有好消息要告诉你:在**.NET 8和C#12**(即将于2023年11月23日发布)中,这个问题将得到解决。
ebdffaop2#
好吧,如果你不能等待/使用.NET 8,你可以尝试在ForEachAsync的帮助下模仿ForAsync,ForEachAsync是从.NET 6开始支持的。在index的情况下循环一些可重用的(数组,列表等):
ForAsync
index
// Must be IEnumerable<T>var data = ...;await Parallel.ForEachAsync(data.Select((value, index) => (value, index)), async (pair, token) => { var value = pair.value; var index = pair.index; //TODO: relevant code here});
// Must be IEnumerable<T>
var data = ...;
await Parallel.ForEachAsync(data.Select((value, index) => (value, index)),
async (pair, token) => {
var value = pair.value;
var index = pair.index;
//TODO: relevant code here
});
字符串如果你想有for (int i = 0; i < n; ++i)循环的xrc版本,
for (int i = 0; i < n; ++i)
int n = ...;await Parallel.ForEachAsync(Enumerable.Range(0, n), async (i, token) => { //TODO: relevant code here});
int n = ...;
await Parallel.ForEachAsync(Enumerable.Range(0, n), async (i, token) => {
型
iecba09b3#
Parallel.ForAsync API将从.NET 8(计划于2023年11月14日发布)开始提供。它具有以下三个重载:
public static Task ForAsync<T>(T fromInclusive, T toExclusive, Func<T, CancellationToken, ValueTask> body) where T : notnull, IBinaryInteger<T>;public static Task ForAsync<T>(T fromInclusive, T toExclusive, CancellationToken cancellationToken, Func<T, CancellationToken, ValueTask> body) where T : notnull, IBinaryInteger<T>;public static Task ForAsync<T>(T fromInclusive, T toExclusive, ParallelOptions parallelOptions, Func<T, CancellationToken, ValueTask> body) where T : notnull, IBinaryInteger<T>;
public static Task ForAsync<T>(T fromInclusive, T toExclusive,
Func<T, CancellationToken, ValueTask> body)
where T : notnull, IBinaryInteger<T>;
CancellationToken cancellationToken, Func<T, CancellationToken, ValueTask> body)
ParallelOptions parallelOptions, Func<T, CancellationToken, ValueTask> body)
字符串它是第一个基于.NET 7中引入的通用数学接口的公共.NET API。使用示例:
ParallelOptions options = new() { MaxDegreeOfParallelism = 2 };await Parallel.ForAsync(0, 100, options, async (i, ct) =>{ // Process the i element (here the type of i is int)});
ParallelOptions options = new() { MaxDegreeOfParallelism = 2 };
await Parallel.ForAsync(0, 100, options, async (i, ct) =>
{
// Process the i element (here the type of i is int)
型有关此API的更多信息和基准测试可以在此Microsoft文档中找到。here也是API提案。
3条答案
按热度按时间gwo2fgha1#
我同意

没有
Parallel.ForAsync
方法看起来是一个巨大的疏忽。不过我有好消息要告诉你:在**.NET 8和C#12**(即将于2023年11月23日发布)中,这个问题将得到解决。ebdffaop2#
好吧,如果你不能等待/使用.NET 8,你可以尝试在
ForEachAsync
的帮助下模仿ForAsync
,ForEachAsync
是从.NET 6开始支持的。在index
的情况下循环一些可重用的(数组,列表等):字符串
如果你想有
for (int i = 0; i < n; ++i)
循环的xrc版本,型
iecba09b3#
Parallel.ForAsync
API将从.NET 8(计划于2023年11月14日发布)开始提供。它具有以下三个重载:字符串
它是第一个基于.NET 7中引入的通用数学接口的公共.NET API。
使用示例:
型
有关此API的更多信息和基准测试可以在此Microsoft文档中找到。here也是API提案。