You're doing it wrong. If you don't have the lock on the object you can't check if it is locked (and if you have the lock you will know in advance). You can "ask" "is locked?" and get a "not" as response, then on the next nanosecond another thread can take the lock and your program will enter in a corrupted state. This simply is not the way to go on multithreaded apps and the reason why .NET does not have a Monitor.IsLocked
method. If your code needs to check the lock before acquire it so you have a design problem. Trying to solve it with unprotected flags is a poor solution that is guaranteed by 100% of chance that will not work.
Anyway, do not use a bool
var to signal multi-thread is locked state (because you can have the same problem, you read "false" and 1 nanosecond later another thread will write "true" to it). Use Interlock.CompareExchange
.
private static int _lockFlag = 0; // 0 - free
if (Interlocked.CompareExchange(ref _lockFlag, 1, 0) == 0){
// only 1 thread will enter here without locking the object/put the
// other threads to sleep.
Monitor.Enter(yourLockObject);
// free the lock.
Interlocked.Decrement(ref _lockFlag);
}
You'll see that you'll need to change the _lockFlag on every place where a lock to your object could be aquired. In other words, you'll construct a custom lock system around the native one.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…