Is there a "try to lock, skip if timed out" operation in C#?

C#MultithreadingLocking

C# Problem Overview


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.

C# Solutions


Solution 1 - C#

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);
    }
}

Solution 2 - C#

I believe that you can use Monitor.TryEnter().

The lock statement just translates to a Monitor.Enter() call and a try catch block.

Solution 3 - C#

I had the same problem, I ended up creating a class TryLock that implements IDisposable and then uses the using statement to control the scope of the lock:

public class TryLock : IDisposable
{
    private object locked;

    public bool HasLock { get; private set; }

    public TryLock(object obj)
    {
        if (Monitor.TryEnter(obj))
        {
            HasLock = true;
            locked = obj;
        }
    }

    public void Dispose()
    {
        if (HasLock)
        {
            Monitor.Exit(locked);
            locked = null;
            HasLock = false;
        }
    }
}

And then use the following syntax to lock:

var obj = new object();

using (var tryLock = new TryLock(obj))
{
    if (tryLock.HasLock)
    {
        Console.WriteLine("Lock acquired..");
    }
}

Solution 4 - C#

Consider using AutoResetEvent and its method WaitOne with a timeout input.

static AutoResetEvent autoEvent = new AutoResetEvent(true);
if(autoEvent.WaitOne(0))
{
    //start critical section
    Console.WriteLine("no other thread here, do your job");
    Thread.Sleep(5000);
    //end critical section
    autoEvent.Set();
}
else
{
    Console.WriteLine("A thread working already at this time.");
}

See https://msdn.microsoft.com/en-us/library/cc189907(v=vs.110).aspx https://msdn.microsoft.com/en-us/library/system.threading.autoresetevent(v=vs.110).aspx and https://msdn.microsoft.com/en-us/library/cc190477(v=vs.110).aspx

Solution 5 - C#

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.

Solution 6 - C#

Based on Dereks answer a little helper method:

private bool TryExecuteLocked(object lockObject, Action action)
{
    if (!Monitor.TryEnter(lockObject))
        return false;

    try
    {
        action();
    }
    finally
    {
        Monitor.Exit(lockObject);
    }

    return true;
}

Usage:

private object _myLockObject;
private void Usage()
{
    if (TryExecuteLocked(_myLockObject, ()=> DoCoolStuff()))
    {
        Console.WriteLine("Hurray!");
    }
}

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
QuestiongilView Question on Stackoverflow
Solution 1 - C#Derek ParkView Answer on Stackoverflow
Solution 2 - C#Ed S.View Answer on Stackoverflow
Solution 3 - C#cwillsView Answer on Stackoverflow
Solution 4 - C#David BurgView Answer on Stackoverflow
Solution 5 - C#Will DeanView Answer on Stackoverflow
Solution 6 - C#AthanvielView Answer on Stackoverflow