使用 Parallel.ForEachAsync

Using Parallel.ForEachAsync

我正在尝试 运行 Parallel.ForEachAsync(),但我遇到了这两个错误:

Error 1:
Argument 2: can not convert from System.Threading.Tasks.ParallelOptions to System.Threading.CancellationToken
Error 2:
Delegate Func<WC, CancellationToken, ValueTask> does not take 1 argument

这是我的代码:

public async Task<List<DisplayDto>> GetData()
{
    var options = new ParallelOptions()
    {
        MaxDegreeOfParallelism = 20;
    };

    await Parallel.ForEachAsync(result, options, async OrderNumber => {
        //Do Stuff here. 
    });
}

必须更改什么才能使其按我的意愿工作?

Parallel.ForEachAsync 预计 Func<TSource,CancellationToken,ValueTask> 即接受 2 个参数(第一个是集合的元素,第二个 - CancellationToken),而不是一个。用法可以是这样的:

public async Task<List<DisplayDto>> GetData()
{
    var options = new ParallelOptions()
    {
        MaxDegreeOfParallelism = 20
    };

    await Parallel.ForEachAsync(result, options, async (OrderNumber, ct) => {
        // do not forget to use CancellationToken (ct) where appropriate 
        // Do Stuff here. 
    });
 }

Example.