C# How to detect an object is already locked

Viewed 52318

How can I detect whether an object is locked or not?

Monitor.TryEnter (as described in Is there a way to detect if an object is locked?) does not work for me because it locks the object if it is not locked.

I only want to check if it is locked and somewhere else in my code I will use the Monitor class to lock the object.

I know it is possible to use for example an boolean field (for example private bool ObjectIsLocked) but what to detect it using the lock-object itself.

The example code below shows what I want to do:

private static object myLockObject = new object();

private void SampleMethod()
{
    if(myLockObject /*is not locked*/) // First check without locking it
    {
        ...
        // The object will be locked some later in the code
        if(!Monitor.TryEnter(myLockObject)) return;

        try
        {

            ....
        }
        catch(){...}
        finally
        {
            Monitor.Exit(myLockObject);
        }
    }
}
6 Answers

I can in no way advocate checking locks then entering code blocks. However, I found this thread while looking for a way to check a new function couldn't leave an object locked. A unit test based on Monitor.IsEntered got me exactly what I was looking for.

Related