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

前端 未结 5 1578
执念已碎
执念已碎 2020-12-23 11:17

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.

5条回答
  •  盖世英雄少女心
    2020-12-23 11:53

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

提交回复
热议问题