我正在尝试将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
时,它只是被阻止,我不明白为什么。
答案 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建议用于新开发的。