Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Disposable reader/writer locks for C#
using System;
using System.Threading;
namespace RwLock
{
public static class ReaderWriterLockSlimExtensions
{
private abstract class LockToken : IDisposable
{
protected ReaderWriterLockSlim RwLock { get; private set; }
protected LockToken(ReaderWriterLockSlim rwLock)
{
RwLock = rwLock;
}
public void Dispose()
{
if (RwLock == null) return;
Exit();
RwLock = null;
}
protected abstract void Exit();
}
private sealed class ReadToken : LockToken
{
public ReadToken(ReaderWriterLockSlim rwLock) : base(rwLock)
{
rwLock.EnterReadLock();
}
protected override void Exit()
{
RwLock.ExitReadLock();
}
}
private sealed class WriteToken : LockToken
{
public WriteToken(ReaderWriterLockSlim rwLock) : base(rwLock)
{
rwLock.EnterWriteLock();
}
protected override void Exit()
{
RwLock.ExitWriteLock();
}
}
public static IDisposable Read(this ReaderWriterLockSlim rwLock)
{
return new ReadToken(rwLock);
}
public static IDisposable Write(this ReaderWriterLockSlim rwLock)
{
return new WriteToken(rwLock);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.