Locking with timeout pattern

后端 未结 1 709
感情败类
感情败类 2021-01-05 06:27

lock uses this pattern

if(Monitor.Enter(lock))
    try
    {
        ...
    }
    finally { Monitor.Exit(lock); } // using this style to reduce         


        
相关标签:
1条回答
  • 2021-01-05 07:24

    I would go with usings for sync lock:

    using System;
    using System.Threading; 
    
    public class MyLock : IDisposable
    {
        private object lockObj;
    
        public MyLock(object lockObj, TimeSpan timeout)
        {
            this.lockObj = lockObj;
            if (!Monitor.TryEnter(this.lockObj, timeout))
                throw new TimeoutException();
        }
    
        public void Dispose()
        {
            Monitor.Exit(lockObj);
        }
    }
    

    Usage:

    using(new MyLock(lockA, new TimeSpan.FromSeconds(1)))
    using(new MyLock(lockB, new TimeSpan.FromSeconds(2)))
    using(new MyLock(lockC, new TimeSpan.FromSeconds(3)))
    {
        // your code
    }
    

    Do not know if "locking" in ctor is good pattern / design, but it will work ;)

    For async. parallelization is not good idea. Why? If some thread will enter the monitor, the same thread must leave it (exit with lock). So if you lock on objA within Parallel.ForEach (f.e.) you will not know which thread has done it. So you won't be able to release it.

    0 讨论(0)
提交回复
热议问题