Adding to a list in a Parallel.ForEach loop in a threadsafe manner
You can use the locking
block like the following code to insert items into your list in a thread-safe manner.
var sync = new object();
var myNewList = new List<SomeObject>();
Parallel.ForEach(myListOfSomethings, a =>
{
// Some other code...
var someObj = new SomeObject();
// More other code...
lock(sync)
{
myNewList.Add(someObj);
}
// Even more code...
});
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<T>
(scroll to the section titled "Thread Safety").
If so, how can I make it threadsafe?
Use a concurrent collection, like ConcurrentBag<T>
. Note that you lose the ability to keep track of the order that items were inserted.