I have objects, they get locks. I want to test if they are locked without acquiring a lock. The idea is if I TryEnter() they i have to Exit() if true to only check the lock correctly.
Seems like a really basic question, how is it done?
I have objects, they get locks. I want to test if they are locked without acquiring a lock. The idea is if I TryEnter() they i have to Exit() if true to only check the lock correctly.
Seems like a really basic question, how is it done?
What possible information can you get from knowing the lock was unlocked back when you looked at it? By the time you make a decision based on that information, the lock may be already taken.
Because the lock statement is equivalent to:
System.Threading.Monitor.Enter(x);
try {
...
}
finally {
System.Threading.Monitor.Exit(x);
}
Can you just do this?
bool ObjectWasUnlocked(object x)
{
if(System.Threading.Monitor.TryEnter(x))
{
System.Threading.Monitor.Exit(x);
return true;
}
else
{
return false;
}
}
Note that I'm naming this function "ObjectWasUnlocked" as opposed to "ObjectIsUnlocked". There is no guarantee that it will still be unlocked when the function has returned.
Here is a related question
http://stackoverflow.com/questions/496388/checking-whether-the-current-thread-owns-a-lock
The conclusion there was 'you can't'