Skip to content

Instantly share code, notes, and snippets.

@rushfrisby
Created June 30, 2015 15:34
Show Gist options
  • Save rushfrisby/3c9847d1fd92cfa9a0ad to your computer and use it in GitHub Desktop.
Save rushfrisby/3c9847d1fd92cfa9a0ad to your computer and use it in GitHub Desktop.
Class that locks on objects in a dictionary by key.
public class KeyLocker : IDisposable
{
private static readonly ConcurrentDictionary<object, object> Locks = new ConcurrentDictionary<object, object>();
private readonly object _locker;
public KeyLocker(object key)
{
_locker = Locks.GetOrAdd(key, new object());
Monitor.Enter(_locker);
}
public void Dispose()
{
Monitor.Exit(_locker);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment