If one thread is adding an object in a List<T>
in C# and other thread is modifying an attribute of an object in the list, is there any possibility of conflict, or .NET has implemented mechanism in the List<T>
that avoids such conflicting situation to happen?

- 34,835
- 7
- 69
- 104

- 2,378
- 5
- 28
- 37
-
2Possible duplicate of [Thread-safe List
property](https://stackoverflow.com/questions/5874317/thread-safe-listt-property) – Samvel Petrosov May 05 '18 at 05:46 -
2Despite what the answers below say, you can safely take a reference to an object stored in the list, and change its properties without changes to the list affecting the object itself. If you manipulate the same object from multiple threads, however, you need to ensure that the object is thread-safe. – ProgrammingLlama May 05 '18 at 06:07
3 Answers
C# Lists are not thread-safe.
.NET Framework 4 introduces thread-safe collections in the System.Collections.Concurrent namespace.
You could use ConcurrentBag<T>
instead of a List<T>

- 495
- 4
- 18
Manipulating objects referenced from the list in concurrent threads can cause conflicts in objects regarding state of the object. Manipulating items in the list can cause conflicts in collections, as many things happen in background, like reallocating buffers or copying elements when adding new items. You have to take care of both. For lists targeting .NET 4 you could use the System.Collections.Concurrent
namespace.

- 34,835
- 7
- 69
- 104

- 1,107
- 9
- 25
Typically there is no built-in protection. There are collections that are thread-safe (see for example https://learn.microsoft.com/en-us/dotnet/api/system.collections.concurrent?view=netframework-4.7.2) and the original collections had a Synchronized property that could be used, but by default collections are not thread safe.

- 5,810
- 2
- 17
- 33