Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 937
Firedragon Avatar asked Nov 18 '11 15:11

Firedragon


3 Answers

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.)

like image 56
mqp Avatar answered Oct 11 '22 15:10

mqp


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.

like image 45
JaredPar Avatar answered Oct 11 '22 13:10

JaredPar


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

like image 22
parapura rajkumar Avatar answered Oct 11 '22 13:10

parapura rajkumar