Karim Karim - 4 months ago 39
C# Question

Is it OK to lock on System.Collections.Generic.List<t>?

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 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.