How long will a C# lock wait, and what if the code crashes during the lock?

C#Locking

C# Problem Overview


I saw the following code, and wanted to use it for a simple activity which may only be executed one at a time, and won't occur frequently (so the chance of occurring twice at a time is very small, but you never know).

So the code:

// class variable
private static object syncRoot = new object();

// in a method:
lock (syncRoot)
{
    DoIt();
}

When another thread comes by and wants to execute the code, how long will it wait until the lock is released? Forever, or can you somehow set a timeout?

And second: if the DoIt() method throws an exception, is the lock still released?

C# Solutions


Solution 1 - C#

>When another thread comes by and wants to execute the code, how long will it wait until the lock is released?

lock will block the the thread trying to enter the lock indefinitely until the object being locked on is released.

>can you somehow set a timeout?

If you need to specify a timeout, use Monitor.TryEnter as in

if(Monitor.TryEnter(obj, new TimeSpan(0, 0, 1))) {
    try {
        body 
    }
    finally {
        Monitor.Exit(obj);
    }
}

>if the DoIt() method throws an exception, is the lock still released?

Yes, a lock(obj) { body } is translated to:

bool lockWasTaken = false;
var temp = obj;
try { Monitor.Enter(temp, ref lockWasTaken); { body } }
finally { if (lockWasTaken) Monitor.Exit(temp); }

For the gory details on what can happen when an exception is thrown, see Locks and exceptions do not mix.

Solution 2 - C#

As mentioned, a regular lock will wait forever, which is a risk of deadlocks.

The preferred mechanism is (and note the ref):

bool lockTaken = false;
try {
    Monitor.TryEnter(lockObj, timeout, ref lockTaken);
    if(!lockTaken) throw new TimeoutException(); // or compensate
    // work here...
} finally {
    if(lockTaken) Monitor.Exit(lockObj);
}

This avoids the risk of not releasing the lock in some edge-cases.

The finally (which exists in any sensible implementation) ensures the lock is released even in error conditions.

Solution 3 - C#

A simple lock(syncRoot) will wait forever.

You can replace it with

if (System.Threading.Monitor.TryEnter(syncRoot, 1000))
{
     try
     {
         DoIt();
     }
     finally
     {
         System.Threading.Monitor.Exit(syncRoot);
     }
}

Every thread should ensure exception-safe locking.

Note that the standard lock(syncRoot) {} is rewritten to Monitor.Enter(syncRoot) and a try/finally

Solution 4 - C#

The lock will wait forever, as Henk said. An exception will still unlock. It is implemented internally with a try-finally block.

Solution 5 - C#

You should take a step back and ask yourself why you are letting an exception from a method have any say over when a Monitor you Enter is Exited. If there's even a chance that DoIt() might throw an exception (and I would argue that if possible you re-write DoIt() so that it DoesNot), then you should have a try/catch block within the lock() statement so that you can ensure you perform any necessary clean-up.

Solution 6 - C#

Know the necessary preconditions for deadlock to take place. Always use Monitor vs Lock to avoid deadlocks.

Conditions

Solution 7 - C#

Jason anwser is excellent, here is a way to wrap it making the call simpler.

    private void LockWithTimeout(object p_oLock, int p_iTimeout, Action p_aAction)
    {
        Exception eLockException = null;
        bool bLockWasTaken = false;
        try
        {
            Monitor.TryEnter(p_oLock, p_iTimeout, ref bLockWasTaken);
            if (bLockWasTaken)
                p_aAction();
            else
                throw new Exception("Timeout exceeded, unable to lock.");
        }
        catch (Exception ex)
        {
            // conserver l'exception
            eLockException = ex;
        }
        finally 
        { 
            // release le lock
            if (bLockWasTaken) 
                Monitor.Exit(p_oLock); 

            // relancer l'exception
            if (eLockException != null)
                throw new Exception("An exception occured during the lock proces.", eLockException);
        }
    }

and then, use it this way:

        // ajouter à la liste des fiches à loader
        LockWithTimeout(m_lLoadingQueue, 3600, () =>
        {
            m_lLoadingQueue.Add(p_efEcranFiche);
        });

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionMichelView Question on Stackoverflow
Solution 1 - C#jasonView Answer on Stackoverflow
Solution 2 - C#Marc GravellView Answer on Stackoverflow
Solution 3 - C#Henk HoltermanView Answer on Stackoverflow
Solution 4 - C#Mr47View Answer on Stackoverflow
Solution 5 - C#dlevView Answer on Stackoverflow
Solution 6 - C#dot.net5000View Answer on Stackoverflow
Solution 7 - C#Sam L.View Answer on Stackoverflow