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

gil picture gil · Aug 12, 2008 · Viewed 26.5k times · Source

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.

Answer

Derek Park picture Derek Park · Aug 12, 2008

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);
    }
}