Threadsafe and general arraylist?

I want to have a common collection of threads, and I saw that Arraylist can easily use thread safety by its static synchronous method, but what mistakes do I have in that this ArrayList is not shared, so when I want to use my objects, I always have to quit. Is there an easier way to do this? Other types of lists are also possible.

+1
collections multithreading c # thread-safety
source share
3 answers

A little knowledge is a dangerous thing ;-) Yes, you could use the Meta Knight offer and use SyncRoot , but you need to be careful - this is not a panacea. See this post from the Team BCL blog from Microsoft to see why it’s not as easy as SyncRoot . Quotes from this post:

Several insightful users of our generic collections have noted that we no longer provide the public SyncRoot property on SyncRoot ICollection<T>

and

I think it’s better for us to make people think more about synchronization, and frankly, the SyncRoot property on our shared collection does not provide any value.

Of course, in order not to say that it cannot be used under any circumstances - you just need to carefully study the use cases and not be on autopilot.

+3
source share

If you read on the MSDN regarding a synchronized method, the following is still said:

"Enumerating through a collection is not essentially a thread-safe procedure. Even when the collection is synchronized, other threads can still modify the collection, which causes the enumerator to throw an exception. To guarantee the safety of the stream during enumeration, you can either block the collection during the whole transfers, or catch exceptions arising from changes made by other threads. "

+3
source share

You can create a List (T) wrapper and synchronize access with the SyncRoot property.

MSDN example:

 ICollection ic = ...; lock (ic.SyncRoot) { // Access the collection. } 
+3
source share

All Articles