SiteMap  | About    

Lock and Monitor in C#

Monitor and Lock in C#

The Lock statement is used in threading, that limit the number of threads that can perform some activity or execute a portion of code at a time. Exclusive locking in threading ensures that one thread does not enter a critical section while another thread is in the critical section of the code.

A lock statement takes a reference to an object which may be “acquired” by a thread; such an object is called a “monitor”. Only one thread may acquire a particular monitor at one time. If a second thread attempts to acquire a particular monitor while a first thread is holding it, and it will wait, block, until the object is released. Once the execution is completed it releases the lock and frees objects.


private static readonly Object myObj = new Object(); lock (myObj) { // critical section }

How does locking work in C# ?

Only one thread can lock the object at a time, and any contending threads are blocked until the lock is released. If more than one thread contends the lock, they are queued on a “ready queue” and granted the lock on a first-come, first-served basis. The bbove code shows first thread enters critical section then it will lock myObj and when other thread tries to enter then it will also try to lock obj which is already locked by first thread, it will have to wait for first thread to release obj. and when first will leave then other thread will lock obj and will enter to critical section.

Monitor.Enter and Monitor.Exit

The lock statement is in fact a syntactic shortcut for a call to the methods Monitor.Enter and Monitor.Exit, with a try/finally block.

bool locked = false; var tempObj = obj; try { Monitor.Enter(tempObj, ref locked); // body } finally { if (locked) { Monitor.Exit(tempObj); } }

The lock keyword calls Enter at the start of the block and Exit at the end of the block and it actually handles Monitor class at back end. It is legal for the same thread to invoke Enter more than once without it blocking; however, an equal number of Exit calls must be invoked before other threads waiting on the object will unblock. Calling Monitor.Exit without first calling Monitor.Enter on the same object throws an exception.

Nested Locking

A thread can repeatedly lock the same object in a nested fashion.

lock (myObj) lock (myObj) lock (myObj) { // critical section } } }

In the above case, the object is unlocked only when the outermost lock statement has exited.


C# Lock Statement VB.Net Lock Statement

A deadlock happens when two threads each wait for a resource held by the other to finish, so neither can proceed. This usually happened in multithreading where a shared resource is locked by one thread and another thread is waiting to access it and something occurs so that the thread holding the locked item is waiting for the other thread to execute.

Check ths simple example to understand DeadLock very clearly:

object firstLock = new object(); object secondLock = new object(); FirstThread void t1() { lock (firstLock) { lock (secondLock) { // critical section } } } SecondThread void t2() { lock (secondLock) { lock (firstLock) { // critical section } } }

In the above program :

FirstThread acquires firstLock.

SecondThread acquires secondLock.

FirstThread attempts to acquire secondLock, but it is already held by SecondThread and thus FirstThread blocks until secondLock is released.

SecondThread attempts to acquire firstLock, but it is held by FirstThread and thus SecondThread blocks until firstLock is released.

At this point, both threads are blocked and will never wake up.

What is lock statement in VB.Net?

Is there a lock statement in VB.NET ?

Yes, it is called SyncLock

SyncLock prevents each thread from entering the block until no other thread is executing it.

VB.Net Example:

SyncLock someLock list.Add(someItem) End SyncLock

How would one do a deep copy in .NET ?

Mark the object with the serialization attribute. Then use the serialization functions.

Related.....Difference between Shallow copy and Deep copy (C) 2016    Founded by raps mk
All Rights Reserved. All other trademarks are property of their respective owners.