Skip to content

Instantly share code, notes, and snippets.

@ReedCopsey
Forked from JohanLarsson/RwLock
Last active August 29, 2015 14:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ReedCopsey/4008cf34becfe332ce08 to your computer and use it in GitHub Desktop.
Save ReedCopsey/4008cf34becfe332ce08 to your computer and use it in GitHub Desktop.
using System;
using System.Threading;
public sealed 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);
}
public void Dispose()
{
if (!_disposed)
{
_disposed = true;
_innerLock.Dispose();
}
}
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();
}
}
}
// 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