Skip to content

Instantly share code, notes, and snippets.

@JohanLarsson
Last active August 29, 2015 14:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save JohanLarsson/c27967a3f74ddf185ae6 to your computer and use it in GitHub Desktop.
Save JohanLarsson/c27967a3f74ddf185ae6 to your computer and use it in GitHub Desktop.
using System;
using System.Threading;
public class RwLock : IDisposable
{
private readonly ReaderWriterLockSlim _innerLock = new ReaderWriterLockSlim();
private bool _disposed = false;
public IDisposable Read()
{
return new Reader(this._innerLock);
}
public IDisposable Write()
{
return new Writer(this._innerLock);
}
/// <summary>
/// Dispose(true); //I am calling you from Dispose, it's safe
/// GC.SuppressFinalize(this); //Hey, GC: don't bother calling finalize later
/// </summary>
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
/// <summary>
/// Protected implementation of Dispose pattern.
/// </summary>
/// <param name="disposing">true: safe to free managed resources</param>
protected virtual void Dispose(bool disposing)
{
if (_disposed)
{
return;
}
if (disposing)
{
_innerLock.Dispose();
}
_disposed = true;
}
private class Reader : IDisposable
{
private readonly ReaderWriterLockSlim _rwLock;
public Reader(ReaderWriterLockSlim rwLock)
{
this._rwLock = rwLock;
this._rwLock.EnterReadLock();
}
public void Dispose()
{
_rwLock.ExitReadLock();
}
}
private class Writer : IDisposable
{
private readonly ReaderWriterLockSlim _rwLock;
public Writer(ReaderWriterLockSlim rwLock)
{
this._rwLock = rwLock;
this._rwLock.EnterWriteLock();
}
public void Dispose()
{
_rwLock.ExitWriteLock();
}
}
private class LockHelper : IDisposable
{
private readonly Action _exitAction;
private bool _disposed = false;
public LockHelper(Action enterAction, Action exitAction)
{
_exitAction = exitAction;
enterAction();
}
/// <summary>
/// Dispose(true); //I am calling you from Dispose, it's safe
/// GC.SuppressFinalize(this); //Hey, GC: don't bother calling finalize later
/// </summary>
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
/// <summary>
/// Protected implementation of Dispose pattern.
/// </summary>
/// <param name="disposing">true: safe to free managed resources</param>
protected virtual void Dispose(bool disposing)
{
if (_disposed)
{
return;
}
if (disposing)
{
_exitAction();
}
_disposed = true;
}
}
}
// Reed Copsey wrote this
type RwLock() =
let rwLock = ReaderWriterLockSlim();
member __.Read() =
rwLock.EnterReadLock()
{ new IDisposable with
member __.Dispose() = rwLock.ExitReadLock()
}
member __.Write() =
rwLock.EnterWriteLock()
{ new IDisposable with
member __.Dispose() = rwLock.ExitWriteLock()
}
interface IDisposable with
member __.Dispose() =
rwLock.Dispose()
using (_rwLock.Read())
{
_innerList.CopyTo(array, arrayIndex);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment