来自异步方法的并行 Foreach 数组

Parallel Foreach array from async method

当从异步方法以并行方式循环数组时出现错误。 调试时,我可以看到 resultsArray 的计数是 11。 但是跨过几次之后,显示“Source array was not long enough” 请问我的代码有什么问题吗?

public async Task<IActionResult> Generate(int id)
{
   List<Product> products = new List<Product>();
    Result[] resultArray = await Manager.GetResultArray();
    Parallel.ForEach(resultArray , result=> //Error here
    {
        SomeMethod(result)); // SomeMethod cast result to Produc class and add to products list
    });
    ...
}

List 不是线程安全集合,您正试图从多个线程更新它。这种情况下可以尝试使用ConcurrentBag

var products = new ConcurrentBag<Product>();
Result[] resultArray = await Manager.GetResultArray();
Parallel.ForEach(resultArray , result=> //Error here
{
    SomeMethod(result)); // SomeMethod should add to ConcurrentBag
});
...