List thread safety

后端 未结 6 817
一生所求
一生所求 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 13:06

    As alternative to the answer of Andrey:

    items.AsParallel().Select(item => SomeProcessingFunc(item)).ToList();
    

    You could also write

    items.AsParallel().ForAll(item => SomeProcessingFunc(item));
    

    This makes the query that is behind it even more efficient because no merge is required, MSDN. Make sure the SomeProcessingFunc function is thread-safe. And I think, but didn't test it, that you still need a lock if the list can be modified in an other thread (adding or removing) elements.

提交回复
热议问题