Skip to content

Instantly share code, notes, and snippets.

@Jalalx
Last active February 5, 2019 15:40
Show Gist options
  • Save Jalalx/babcb8796c2eb6444953ac38ec4dada7 to your computer and use it in GitHub Desktop.
Save Jalalx/babcb8796c2eb6444953ac38ec4dada7 to your computer and use it in GitHub Desktop.
Creates a conditional lock based on given boolean and a key. Threads with same key will be locked.
public class SharedConditionalLock : IDisposable
{
private static readonly ConcurrentDictionary<string, object> _locks = new ConcurrentDictionary<string, object>();
public SharedConditionalLock(string key, bool isEnabled)
{
Key = key;
IsEnabled = isEnabled;
if (isEnabled)
{
Monitor.Enter(_locks.GetOrAdd(Key, new object()));
}
}
public bool IsEnabled { get; }
public string Key { get; }
public void Dispose()
{
if (IsEnabled)
{
Monitor.Exit(_locks[Key]);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment