Got “Index out of bounds” Error on List.Add() in c#

前端 未结 2 1162
刺人心
刺人心 2021-01-04 03:48

Here is the code

List something = new List();
Parallel.ForEach(anotherList, r =>
     {
            .. do some work
                   


        
相关标签:
2条回答
  • 2021-01-04 04:06

    In order to prevent the issue, instead of List you may use ConcurrentQueue or similar Concurrent collections in your parallel part. Once the parallel task is done, you can put it in the List<T>.

    For more information take a look at System.Collections.Concurrent namespace to find the suitable collection for your use case.

    0 讨论(0)
  • 2021-01-04 04:21

    I found that lock (yourObject) also negates the threading problem

    0 讨论(0)
提交回复
热议问题