views:

831

answers:

3

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.

+7  A: 

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 Swangren
+9  A: 

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);
    }
}
Derek Park
+2  A: 

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.

Will Dean