我有一个异步代码,如下所示:
List<Task<(decimal, decimal)?>> tasks = offsets
.Zip(prices, async (offset, price) => await Func(offset, price));
(decimal, decimal)?[] result = await Task.WhenAll(tasks);
我想用
Parallel
代替。
但是
ParallelLoopResult result1 = Parallel.ForEachAsync(
offsets.Zip(prices, (offset, price) => await Func(offset, price));
不起作用,因为 foreach 仅需要 1 个参数。 知道我该怎么做吗?
这应该编译:
ParallelOptions parallelOptions = new()
{
MaxDegreeOfParallelism = 2
};
await Parallel.ForEachAsync(offsets.Zip(prices), parallelOptions, async (pair, ct) =>
{
var (offset, price) = pair;
await Func(offset, price);
});
Parallel.ForEachAsync
重载:
public static Task ForEachAsync<TSource>(
IEnumerable<TSource> source,
ParallelOptions parallelOptions,
Func<TSource, CancellationToken, ValueTask> body);