Created
October 26, 2019 04:08
-
-
Save ikriv/c9a3018e98ecce3d1392c090ed54052d to your computer and use it in GitHub Desktop.
Disposable reader/writer locks for C#
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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