尝试读取资源时 ReaderWriterLock 阻塞
ReaderWriterLock blocks when trying to read resource
我正在尝试使用 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
时,它只是阻塞,我不明白为什么。
看看 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 推荐用于新开发。
我正在尝试使用 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
时,它只是阻塞,我不明白为什么。
看看 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 推荐用于新开发。