Thursday, February 3, 2011

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

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.

  • I believe that you can use Monitor.TryEnter(). Here is the MSDN entry

    http://msdn.microsoft.com/en-us/library/system.threading.monitor.tryenter(VS.71).aspx

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

    @Jeff: Thanks for the edit, I need to go and look at the markdown syntax.

  • 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);
        }
    }
    
    From Derek Park
  • 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.

    From Will Dean

0 comments:

Post a Comment