Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 494
gil Avatar asked Aug 12 '08 06:08

gil


People also ask

Why is an int in C not a good lock?

Integers can not be used with lock because they are boxed (and lock only locks on references). The scenario is as follows: I have a forum based website with a moderation feature. What I want to do is make sure that no more than one moderator can moderate a post at any given time.

Why do we use lock statement in C?

The lock statement acquires the mutual-exclusion lock for a given object, executes a statement block, and then releases the lock. While a lock is held, the thread that holds the lock can again acquire and release the lock. Any other thread is blocked from acquiring the lock and waits until the lock is released.

What is lock in c3?

The lock keyword is used to get a lock for a single thread. A lock prevents several threads from accessing a resource simultaneously. Typically, you want threads to run concurrently. Using the lock in C#, we can prevent one thread from changing our code while another does so.


3 Answers

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);
    }
}
like image 140
Derek Park Avatar answered Nov 06 '22 02:11

Derek Park


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

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

like image 29
Ed S. Avatar answered Nov 06 '22 02:11

Ed S.


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..");
    }
}
like image 18
cwills Avatar answered Nov 06 '22 03:11

cwills