Hugo Mota
Hugo Mota

Reputation: 11567

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

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.

Upvotes: 8

Views: 146

Answers (1)

Dmitrii Bychenko
Dmitrii Bychenko

Reputation: 186823

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);
 } 

Upvotes: 7

Related Questions