Is there a "try to lock, skip if timed out" operation in C#?

Viewed 30479

I need to try to lock on an object, and if its already locked just continue (after time out, or without it).

The C# lock statement is blocking.

6 Answers

Ed's got the right function for you. Just don't forget to call Monitor.Exit(). You should use a try-finally block to guarantee proper cleanup.

if (Monitor.TryEnter(someObject))
{
    try
    {
        // use object
    }
    finally
    {
        Monitor.Exit(someObject);
    }
}

I believe that you can use Monitor.TryEnter().

The lock statement just translates to a Monitor.Enter() call and a try catch block.

You'll probably find this out for yourself now that the others have pointed you in the right direction, but TryEnter can also take a timeout parameter.

Jeff Richter's "CLR Via C#" is an excellent book on details of CLR innards if you're getting into more complicated stuff.

Based on Dereks answer a little helper method:

private bool TryExecuteLocked(object lockObject, Action action)
{
    if (!Monitor.TryEnter(lockObject))
        return false;

    try
    {
        action();
    }
    finally
    {
        Monitor.Exit(lockObject);
    }

    return true;
}

Usage:

private object _myLockObject;
private void Usage()
{
    if (TryExecuteLocked(_myLockObject, ()=> DoCoolStuff()))
    {
        Console.WriteLine("Hurray!");
    }
}
Related