Last active
January 7, 2024 15:13
-
-
Save rwhitmire/12a2a1665fc9deed43d65765fdc58eef to your computer and use it in GitHub Desktop.
C# key-based locks
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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