Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why lock on Collection.SyncRoot instead of just lock the collection?

I'm trying to understand the point of the syncroot in ICollection. Why not just lock the collection?

lock(myCollection)
{
    //do stuff to myCollection
}

vs

lock(myCollection.SyncRoot)
{
    //do stuff to myCollection
}
like image 482
richard Avatar asked Jun 29 '11 17:06

richard


People also ask

What is lock in threading?

For a thread to work on an object, it must have control over the lock associated with it, it must “hold” the lock. Only one thread can hold a lock at a time. If a thread tries to take a lock that is already held by another thread, then it must wait until the lock is released.

Can two threads acquire the same lock?

Typically, threads cannot acquire locks twice in a row: a thread must release an acquired lock before attempting to acquire it again. However, reentrant locks can be acquired multiple times by the same thread. Reentrant locks allow code to acquire a lock before calling other functions that acquire the same lock.

What is SyncRoot C#?

CSharp Online Training SyncRoot property is used to get an object that can be used to synchronize access to the Array. The classes that have arrays can also use the SyncRoot property to implement their own synchronization. Enumerating through a collection is not a thread safe procedure.

Why do we need locks?

Locks are used to make a river more easily navigable, or to allow a canal to cross land that is not level. Later canals used more and larger locks to allow a more direct route to be taken.


1 Answers

Typically, if thread safety is a serious concern, I would avoid either of these options.

A far better option is typically to maintain your own private variable, and lock on it in all methods where it's required - including the entire public API that accesses the collection.

The real danger is that, by locking on a type that's exposed or could be exposed to the outside world, you potentially open up the ability for the "outside world" to mess with your synchronization. If more than one lock is being used, this can lead to dead locks (if the outside locks on something you aren't expecting).

By creating a private variable, and locking exclusively on it, you're "taking control" of the situation. This makes it much more clear what is occurring. In addition, it eases synchronization between multiple objects, especially later as you maintain the code, since the lock is very clear.

like image 151
Reed Copsey Avatar answered Nov 14 '22 22:11

Reed Copsey