Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

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?

like image 348
Karim Avatar asked Nov 14 '09 18:11

Karim


People also ask

What is List T?

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 define generic List in c#?

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.


1 Answers

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.

like image 191
Nader Shirazie Avatar answered Nov 16 '22 02:11

Nader Shirazie