Skip to content

Instantly share code, notes, and snippets.

@rwhitmire
Last active January 7, 2024 15:13
Show Gist options
  • Save rwhitmire/12a2a1665fc9deed43d65765fdc58eef to your computer and use it in GitHub Desktop.
Save rwhitmire/12a2a1665fc9deed43d65765fdc58eef to your computer and use it in GitHub Desktop.
C# key-based locks
public class LockManager
{
private readonly SemaphoreSlim[] _semaphores;
public LockManager()
{
_semaphores = new SemaphoreSlim[1000];
for(var i = 0; i < _semaphores.Length; i++)
{
_semaphores[i] = new SemaphoreSlim(1);
}
}
public async Task<T> WaitForLockAsync<T>(string key, Func<Task<T>> func)
{
var semaphore = _semaphores[CalculateHash(key)];
try
{
await semaphore.WaitAsync();
return await func.Invoke();
}
finally
{
semaphore.Release();
}
}
private uint CalculateHash(string key)
{
return (uint)key.GetHashCode() % (uint)_semaphores.Length;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment