I have been reading about the syncroot element but I can't find it in the List type. So how should the multithreading synchronization be done with the System.Collections.Generic.List<> type?
The List<T> is a collection of strongly typed objects that can be accessed by index and having methods for sorting, searching, and modifying list. It is the generic version of the ArrayList that comes under System.
How to Add Elements into a Generic List<T> Collection in C#? If you want to add elements to the generic list collection then you need to use the following Add() and AddRange() method of the Generic List Collection Class in C#. Add(T item): The Add(T item) method is used to add an element to the end of the Generic List.
The reason you can't find it is because it was explicitly removed. If it is really what you want to do, use a SynchronizedCollection<T>
or create a dedicated synchronization object. The best approach (in general) is to create a dedicated synchronization object, as Winston illustrates.
The essential problem with the SyncRoot
property is that it provides a false sense of security -- it only handles a very narrow set of circumstances. Developers often neglect synchronization for an entire logical operation, assuming that locking on SyncRoot
is good enough.
You generally want to avoid locking on a type (List<T>
in this case). If, for example, you have two instances of your type, or another type were to also use a lock on List<T>
, they would all competing for a single global lock. Really, what you are trying to achieve is proper synchronization for a single object.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With