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
 });
 ...
}
asked Jun 27, 2020 at 15:31
3

1 Answer 1

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
});
...
answered Jun 27, 2020 at 16:07

1 Comment

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?

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.