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?
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.
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.
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.
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.
lock
is a wrapper for Monitor.Enter
and Monitor.Exit
:
The
lock
keyword callsEnter
at the start of the block andExit
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 ofExit
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 ifInterrupt
interrupts a thread that is waiting to enter alock
statement.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With