Skip to content

Instantly share code, notes, and snippets.

@0x49D1
Created January 21, 2022 10:26
Show Gist options
  • Save 0x49D1/9ae9a5b9edd33b30019b3590630961d8 to your computer and use it in GitHub Desktop.
Save 0x49D1/9ae9a5b9edd33b30019b3590630961d8 to your computer and use it in GitHub Desktop.
Named locker example. Not to use same lock object for all locking constructs, because sometimes it will lock different procedures in same code block. For example get/set cache with cache key argument.
public class NamedLocker
{
private readonly ConcurrentDictionary<string, object> _lockDict = new ConcurrentDictionary<string, object>();
// Get a lock for use with a lock(){} block
public object GetLock(string name)
{
return _lockDict.GetOrAdd(name, s => new object());
}
// Run a short lock inline using a lambda
public TResult RunWithLock<TResult>(string name, Func<TResult> body)
{
lock (_lockDict.GetOrAdd(name, s => new object()))
return body();
}
// Run a short lock inline using a lambda void
public void RunWithLock(string name, Action body)
{
lock (_lockDict.GetOrAdd(name, s => new object()))
body();
}
// Remove an old lock object that is no longer needed
public void RemoveLock(string name)
{
object o;
_lockDict.TryRemove(name, out o);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment