尝试读取资源时,ReaderWriterLock会阻塞

时间:2019-05-06 14:16:20

标签: .net-core task-parallel-library readerwriterlock

我正在尝试将ReaderWriterLock用于两个Tasks之间的共享资源。由于某种原因,它开始无限期地等待:

class State {

        private const int TIMEOUT = 5000;
        private ReaderWriterLock lck = new ReaderWriterLock();
        private TimeSpan lastIssuedAt;

        public TimeSpan LastIssuedAt {
            get {

                this.lck.AcquireReaderLock(TIMEOUT);
                return this.lastIssuedAt;
            }
            set {
                this.lck.AcquireWriterLock(TIMEOUT);
                this.lastIssuedAt = value;
            }
        }
}

当任务尝试get属性LastIssuedAt时,它只是被阻止,我不明白为什么。

1 个答案:

答案 0 :(得分:1)

看看MSDN上的示例:https://docs.microsoft.com/en-us/dotnet/api/system.threading.readerwriterlock?view=netframework-4.8

您忘记释放锁。这样做的常见模式是try / finally:

ReaderWriterLock lck = new ReaderWriterLock();

lck.AcquireReaderLock(timeOut);
try
{
    // Do what needs to be done under the lock
}
finally 
{
    // Ensure that the lock is released.
    lck.ReleaseReaderLock();
}

另外,请查看ReaderWriterLockSlim:https://docs.microsoft.com/en-us/dotnet/api/system.threading.readerwriterlockslim?view=netframework-4.8 MSDN建议用于新开发的。