Adding to a list in a Parallel.ForEach loop in a threadsafe manner

前端 未结 3 568
不知归路
不知归路 2020-12-06 01:28

I have a bit of code that works like this on a list of obj objects called ListofObjects:

List NewListofObjects();

Parall         


        
3条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-06 02:12

    Is this because my NewListofObjects.Add(newobj) method is not threadsafe?

    Correct. It is not threadsafe.

    Any instance members are not guaranteed to be thread safe.

    That's from MSDN referring to List (scroll to the section titled "Thread Safety").

    If so, how can I make it threadsafe?

    Use a concurrent collection, like ConcurrentBag. Note that you lose the ability to keep track of the order that items were inserted.

提交回复
热议问题