Reputation: 11567
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
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