Does Monitor.TryEnter and lock () work together?

I look at the code that was created and it uses TryEnter in one method call and blocks the 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
    }
}

This is normal?

+5
source share
3 answers
Lock

blocked until the resource is available

TryEnter will not do anything if it is already locked.

Depending on your needs, you should use one or the other.

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

+2
+8

, . # lock - Monitor.Enter Monitor.TryEnter.

. Type . , , . .

+4
source

All Articles