Firedragon
Firedragon

Reputation: 3733

Does Monitor.TryEnter and lock() work together?

I am looking at code that has been created and it uses a TryEnter in one method call and lock in others. So, like this:

private readonly object xmppLock = new object();

void f1() 
{
    if (Monitor.TryEnter(xmppLock))
    {
        try
        {
            // Do stuff
        }
        finally
        {
            Monitor.Exit(xmppLock);
        }
    }
}

void f2()
{
    lock(xmppLock)
    {
        // Do stuff
    }
}

Is this okay?

Upvotes: 7

Views: 5659

Answers (3)

JaredPar
JaredPar

Reputation: 754715

Yes these two constructs will work together. The C# lock keyword is just a thin wrapper over the Monitor.Enter and Monitor.TryEnter methods.

Note: I would absolutely avoid using a Type instance as the value to lock on. Doing so is very fragile as it makes it very easy for two completely unrelated pieces of code to be unexpectedly locking on the same object. This can lead to deadlocks.

Upvotes: 7

mqp
mqp

Reputation: 71935

lock is just syntax sugar for Monitor.Enter, so yes, it will work fine.

The Visual Basic SyncLock and C# lock statements use Monitor.Enter to take the lock and Monitor.Exit to release it. The advantage of using the language statements is that everything in the lock or SyncLock block is included in a Try statement.

(That said, it's considered poor form to lock on something public like a Type object.)

Upvotes: 11

parapura rajkumar
parapura rajkumar

Reputation: 24403

lock will block until the resource is available

TryEnter will not do anything if it is already locked.

Depending on your needs you have to use one or the other.

In your case f2() will always do what ever it does no matter how long it takes. f1() will return immediately if there is lock contention

Upvotes: 2

Related Questions