[英]Is there an equivalent of the lock{} statement for ReaderWriterLockSlim?
I like the shortcut in C# of lock(myLock){ /* do stuff */}
. 我喜欢C#of
lock(myLock){ /* do stuff */}
的快捷方式lock(myLock){ /* do stuff */}
。 Is there an equivalent for read/write locks? 是否有读/写锁的等价物? (Specifically ReaderWriterLockSlim.) Right now, I use the following custom method, which I think works, but is kind of annoying because I have to pass in my action as an anonymous function, and I would prefer to use a standard locking mechanism if possible.
(特别是ReaderWriterLockSlim。)现在,我使用以下自定义方法,我认为它有效,但有点烦人,因为我必须将我的操作作为匿名函数传递,我宁愿使用标准锁定机制,如果可能的话。
void bool DoWithWriteLock(ReaderWriterLockSlim RWLock, int TimeOut, Action Fn)
{
bool holdingLock = false;
try
{
if (RWLock.TryEnterWriteLock(TimeOut))
{
holdingLock = true;
Fn();
}
}
finally
{
if (holdingLock)
{
RWLock.ExitWriteLock();
}
}
return holdingLock;
}
You can't override the behaviour of the lock
keyword. 您无法覆盖
lock
关键字的行为。 A common technique is to hijack the using
keyword. 一种常见的技术是劫持
using
关键字。
DoWithWriteLock
return an IDisposable
DoWithWriteLock
返回IDisposable
TryEnterWriteLock
call inside the DoWithWriteLock
method TryEnterWriteLock
调用保留在DoWithWriteLock
方法中 IDisposable
. IDisposable
的对象。 In that object's Dispose
method, put the call to ExitWriteLock
. Dispose
方法中,将调用放到ExitWriteLock
。 The end result: 最终结果:
// Before
DoWithWriteLock(rwLock,
delegate
{
Do1();
Do2()
} );
// After
using (DoWithWriteLock(rwLock))
{
Do1();
Do2();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.