Created
October 21, 2015 17:22
-
-
Save mscottreed/4802b0be7ef72212d1e0 to your computer and use it in GitHub Desktop.
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
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