Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I check if current code is "inside" lock?

Tags:

c#

I have some code that can be called from inside or outside a lock. I need to do stuff when inside the lock. The code itself has no knowledge of where it's being called from. So, I need something like this:

lock (MyLock) {
    if (INSIDE_LOCK) ...
}

I know it sounds weird and wrong but I need this for compatibility issues. Otherwise I will have to rewrite a lot of code, which would be risky since I have no tests.

like image 784
Hugo Mota Avatar asked Aug 03 '16 14:08

Hugo Mota


1 Answers

Try Monitor class:

 if (Monitor.IsEntered(MyLock)) {...}

Since (see René Vogt comment below) lock

 lock(MyLock) {
   ...
 }

is, in fact a syntactic sugar for

 Monitor.Enter(MyLock);

 try {
   ... 
 }  
 finally {
   Monitor.Leave(MyLock);
 } 
like image 61
Dmitry Bychenko Avatar answered Oct 22 '22 00:10

Dmitry Bychenko