我有一些问题ReaderWriterLockSlim
。我无法理解它是如何发挥作用的。
My code:
private async Task LoadIndex()
{
if (!File.Exists(FileName + ".index.txt"))
{
return;
}
_indexLock.EnterWriteLock();// <1>
_index.Clear();
using (TextReader index = File.OpenText(FileName + ".index.txt"))
{
string s;
while (null != (s = await index.ReadLineAsync()))
{
var ss = s.Split(':');
_index.Add(ss[0], Convert.ToInt64(ss[1]));
}
}
_indexLock.ExitWriteLock();<2>
}
当我在 处输入写锁定时,在调试器中我可以看到_indexLock.IsWriteLockHeld
is true
,但是当执行到 时我看到_indexLock.IsWriteLockHeld
is false
and _indexLock.ExitWriteLock
抛出异常SynchronizationLockException
并显示消息“写锁正在被释放而不被保留”。我做错了什么?
ReaderWriterLockSlim
是线程仿射锁类型,因此通常不能与async
and await
.
你应该使用SemaphoreSlim
with WaitAsync
,或者(如果你really需要读/写锁),使用我的AsyncReaderWriterLock来自 AsyncEx https://github.com/StephenCleary/AsyncEx/blob/master/doc/AsyncReaderWriterLock.md or 史蒂芬·图布的AsyncReaderWriterLock https://devblogs.microsoft.com/pfxteam/building-async-coordination-primitives-part-7-asyncreaderwriterlock/.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)