Parallel with Zip lists in C#

55 Views Asked by At

I have a code in async that looks like this:

List<Task<(decimal, decimal)?>> tasks = offsets
    .Zip(prices, async (offset, price) => await Func(offset, price));

(decimal, decimal)?[] result = await Task.WhenAll(tasks);

And I would like to use Parallel instead. but

ParallelLoopResult result1 = Parallel.ForEachAsync(
    offsets.Zip(prices, (offset, price) => await Func(offset, price));

does not work as foreach takes only 1 argument. Any idea how I could do that please?

1

There are 1 best solutions below

0
Theodor Zoulias On BEST ANSWER

This should compile:

ParallelOptions parallelOptions = new()
{
    MaxDegreeOfParallelism = 2 // Configurable
};

await Parallel.ForEachAsync(offsets.Zip(prices), parallelOptions, async (pair, ct) =>
{
    var (offset, price) = pair;
    await Func(offset, price);
});

It uses this Parallel.ForEachAsync overload:

public static Task ForEachAsync<TSource>(
    IEnumerable<TSource> source,
    ParallelOptions parallelOptions,
    Func<TSource, CancellationToken, ValueTask> body);