Cross-process read-write synchronization primative in .NET?

后端 未结 5 771
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-02-06 08:07

Is there a read/write locking mechanism that works across processes (similar to Mutex, but read/write instead exclusive locking)? I would like to allow concurrent read access,

5条回答
  •  迷失自我
    2021-02-06 08:57

    I've created this class based on Pavel's answer. I haven't tested it extensively yet, but I've created a simple winforms application to test it and so far it works well.

    Please note, that it uses a semaphore, so it doesn't support reentrancy.

    public class CrossProcessReaderWriterLock
    {
        private readonly string _name;
        const int _maxReaders = 10;
    
        readonly Mutex     _mutex;
        readonly Semaphore _semaphore;
    
        public CrossProcessReaderWriterLock(string name)
        {
            _name = name;
            _mutex     = new Mutex(false, name + ".Mutex");
            _semaphore = new Semaphore(_maxReaders, _maxReaders, name + ".Semaphore");
        }
    
        public void AcquireReaderLock()
        {
            //Log.Info($"{_name} acquiring reader lock...");
    
            _mutex    .WaitOne();
            _semaphore.WaitOne();
            _mutex    .ReleaseMutex();
    
            //Log.Info($"{_name} reader lock acquired.");
        }
    
        public void ReleaseReaderLock()
        {
            _semaphore.Release();
    
            //Log.Info($"{_name} reader lock released.");
        }
    
        public void AcquireWriterLock()
        {
            //Log.Info($"{_name} acquiring writer lock...");
    
            _mutex.WaitOne();
    
            for (int i = 0; i < _maxReaders; i++)
                _semaphore.WaitOne(); // drain out all readers-in-progress
    
            _mutex.ReleaseMutex();
    
            //Log.Info($"{_name} writer lock acquired.");
        }
    
        public void ReleaseWriterLock()
        {
            for (int i = 0; i < _maxReaders; i++)
                _semaphore.Release();
    
            //Log.Info($"{_name} writer lock released.");
        }
    }
    

提交回复
热议问题