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

c#, multithreading

Solution

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.

Problem

I have a bit of code that works like this on a list of obj objects called ListofObjects: ``` List<SomeObject> NewListofObjects<SomeObject>(); Parallel.ForEach(ListofObjects, obj => //Do some operations here on obj to get a newobj NewListofObjects.Add(newobj); ); ``` Now I am out of the Parallel.ForEach loop, and I want to do an operation on NewListofObjects. However, I get this error when I try to: "Attempted to read or write protected memory. This is often an indication that other memory is corrupt". Is this because my NewListofObjects.Add(newobj) method is not threadsafe? If so, how can I make it threadsafe?

Original source