List thread safety

后端 未结 6 836
一生所求
一生所求 2020-11-28 12:33

I am using the below code

var processed = new List();
Parallel.ForEach(items, item => 
{
    processed.Add(SomeProcessingFunc(item));
});
         


        
6条回答
  •  我在风中等你
    2020-11-28 12:58

    reading is thread safe, but adding is not. You need a reader/writer lock setup as adding may cause the internal array to resize which would mess up a concurrent read.

    If you can guarantee the array won't resize on add, you may be safe to add while reading, but don't quote me on that.

    But really, a list is just an interface to an array.

提交回复
热议问题