An asynchronous .NET library that allows you to lock based on a key (keyed semaphores), limiting concurrent threads sharing the same key to a specified number, with optional pooling for reducing memory allocations.
$ dotnet add package AsyncKeyedLockAn asynchronous .NET Standard 2.0 library that allows you to lock based on a key.
The recommended means is to use NuGet, but you could also download the source code from here.
var asyncKeyedLocker = new AsyncKeyedLocker();
using (var lockObj = await asyncKeyedLocker.LockAsync(myObject))
{
...
}
You can also set the maximum number of requests for the semaphore that can be granted concurrently (set to 1 by default):
var asyncKeyedLocker = new AsyncKeyedLocker(2);
If you would like to see how many concurrent requests there are for a semaphore for a given key:
int myCount = asyncKeyedLocker.GetCount(myObject);
And if for some reason you need to force release the requests in the semaphore for a key:
asyncKeyedLocker.ForceRelease(myObject);
You may also use Dependency Injection to inject an instance of AsyncKeyedLock.
This library is based on Stephen Cleary's solution.