Skip to content

Instantly share code, notes, and snippets.

@mscottreed
Created October 21, 2015 17:22
Show Gist options
  • Save mscottreed/4802b0be7ef72212d1e0 to your computer and use it in GitHub Desktop.
Save mscottreed/4802b0be7ef72212d1e0 to your computer and use it in GitHub Desktop.
public struct AllocatedLock : IDisposable
{
private readonly object _toLock;
public AllocatedLock(object toLock)
{
_toLock = toLock;
}
public void Dispose()
{
Monitor.Exit(_toLock);
}
}
public static AllocatedLock Lock(this object toLock, TimeSpan timeout)
{
if (Monitor.TryEnter(toLock, timeout))
{
return new AllocatedLock(toLock);
}
else
{
throw new TimeoutException(string.Format("Failed to get lock within {0}", timeout));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment