1

I am getting an error when looping array from async method as Parallel. When debuging, I can see count of the resultsArray is 11. But after stepping over a few times, it showed me "Source array was not long enough" Can I please get what the issue of my code?

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
    });
    ...
}
dbenbyeon
  • 145
  • 2
  • 6
  • Take a look at these two. https://stackoverflow.com/questions/42007593/getting-exception-when-working-with-list-and-parallel-loops https://stackoverflow.com/questions/10362023/destination-array-not-long-enough/14118859 – Efe Zaladin Jun 27 '20 at 15:40
  • Can you please add code for your `SomeMethod` and `Result` class? – Guru Stron Jun 27 '20 at 15:46
  • @GuruStron I can't put the exact code but added some changes...hope this helps – dbenbyeon Jun 27 '20 at 16:00

1 Answers1

1

List is not an thread safe collection, which you are trying to update from multiple threads. You can try to use ConcurrentBag in this case:

var products = new ConcurrentBag<Product>();
Result[] resultArray = await Manager.GetResultArray();
Parallel.ForEach(resultArray , result=> //Error here
{
    SomeMethod(result)); // SomeMethod should add to ConcurrentBag
});
...
Guru Stron
  • 102,774
  • 10
  • 95
  • 132
  • Thanks Guru, I didn't know the List is not a thread safe. Could you please explain why the List is not a thread safe? – dbenbyeon Jun 28 '20 at 13:19