Reputation: 2568
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?
Upvotes: 1
Views: 14539
Reputation: 1167
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.
Upvotes: 2
Reputation: 503
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>
Upvotes: 4
Reputation: 6233
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.
Upvotes: 1