ReaderWriterLockSlim 扩展
通过使用读/写扩展,使您的同步更加容易。
引言
我想很多人可能已经自己做过这个了。 但如果您还没有为 ReadWriterLockSlim
(或任何其他锁类)编写读/写扩展,那么这里为您提供。
背景
我发现自己太常编写以下模式了:
bool lockHeld = false; try { lockHeld = rwlock.EnterReadLock(); closure(); } finally { if (lockHeld) rwlock.ExitReadLock(); }
我也需要一种以相同方式使用超时进入锁的方式。 所以我首先创建了以下扩展
public static bool EnterReadLock(this ReaderWriterLockSlim target, int? millisecondsTimeout, bool throwsOnTimeout = false) { if (millisecondsTimeout == null) target.EnterReadLock(); else if (!target.TryEnterReadLock(millisecondsTimeout.Value)) { if (throwsOnTimeout) throw new TimeoutException( "Could not gain a read lock within the timeout specified. " + "(millisecondsTimeout=" + millisecondsTimeout.Value + ") "); return false; } return true; }
这促使我编写一组如下所示的扩展
public static bool Read(this ReaderWriterLockSlim target, Action closure, int? millisecondsTimeout = null, bool throwsOnTimeout = false) { Contract.Requires<ArgumentNullException>(closure != null); Contract.Requires<ArgumentOutOfRangeException>( millisecondsTimeout == null || millisecondsTimeout >= 0 ); bool lockHeld = false; try { lockHeld = target.EnterReadLock(millisecondsTimeout, throwsOnTimeout); closure(); } finally { if (lockHeld) target.ExitReadLock(); } return lockHeld; }
最终得到一些非常灵活和强大的委托扩展。
使用示例
再简单不过了rwlock.Read( ()=> { /* Some read operation */ } );
if( !rwlock.Read( ()=> { /* Some read operation */ }, 1000 ) )
{ // Was unable to get a read lock within 1 second?
/* Do something else */
}
int myValue = rwlock.ReadValue( ()=>
{
int value;
/* Get the value */
return value;
} );
rwlock.ReadUpgradable( ()=>
{
if(needsWrite()) { // Do verification before writing...
rwlock.Write(()=>{
/* Do write operation */
}
}
}
下载代码以获取更多有用的扩展。