Skip to content

Instantly share code, notes, and snippets.

@winkel
Created October 16, 2013 18:06
Show Gist options
  • Save winkel/7012168 to your computer and use it in GitHub Desktop.
Save winkel/7012168 to your computer and use it in GitHub Desktop.
LockHolder
object lockHandle = new object();
using (LockHolder<object> lockObj = new LockHolder<object>
(lockHandle, 1000))
{
if (lockObj.LockSuccessful)
{
// work elided
}
}
// Dispose called here.
// http://www.informit.com/articles/article.aspx?p=1231461
public sealed class LockHolder<T> : IDisposable where T : class
{
private T handle;
private bool holdsLock;
public LockHolder(T handle, int milliSecondTimeout)
{
this.handle = handle;
holdsLock = System.Threading.Monitor.TryEnter(
handle, milliSecondTimeout);
}
public bool LockSuccessful
{
get { return holdsLock; }
}
#region IDisposable Members
public void Dispose()
{
if (holdsLock)
System.Threading.Monitor.Exit(handle);
// Don’t unlock twice
holdsLock = false;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment