Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

lock inside lock

Tags:

c#

locking

I'm wondering if this construction will cause an error:

lock(sync) {   // something   lock(sync)   {     //something     lock(sync)     {       //something     }   } } 

I've run this code, and it seems fine, but maybe in some circumstances an error may be thrown?

like image 799
reizals Avatar asked Feb 07 '12 08:02

reizals


People also ask

What does lock () return when a the lock is being held?

While a lock is held, the thread that holds the lock can again acquire and release the lock. Any other thread is blocked from acquiring the lock and waits until the lock is released. Since the code uses a try... finally block, the lock is released even if an exception is thrown within the body of a lock statement.

What is lock C#?

C# Lock keyword ensures that one thread is executing a piece of code at one time. The lock keyword ensures that one thread does not enter a critical section of code while another thread is in that critical section. Lock is a keyword shortcut for acquiring a lock for the piece of code for only one thread.

What is lock mechanism?

A locking mechanism is a mechanical system which provides assistance to the coupling and uncoupling of two connectors and the fixation of the two parts in operating position. The locking system helps to maintain the primary function of electrical continuity and is involved in the sealing performances of products.

Why should you avoid the lock keyword?

Avoid using 'lock keyword' on string object String object: Avoid using lock statements on string objects, because the interned strings are essentially global in nature and may be blocked by other threads without your knowledge, which can cause a deadlock.


1 Answers

lock is a wrapper for Monitor.Enter and Monitor.Exit:

The lock keyword calls Enter at the start of the block and Exit at the end of the block. From the former's documentation:

From the documentation for Monitor.Enter:

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.

Because the calls to Enter and Exit are paired, your code pattern has well defined behaviour.

Note, however, that lock is not guaranteed to be an exception-less construct:

A ThreadInterruptedException is thrown if Interrupt interrupts a thread that is waiting to enter a lock statement.

like image 155
ta.speot.is Avatar answered Oct 09 '22 20:10

ta.speot.is