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 AsyncKeyedLock
AsyncKeyedLockAn asynchronous .NET Standard 2.0 library that allows you to lock based on a key (keyed semaphores), only allowing a defined number of concurrent threads that share the same key.
For example, if you're processing transactions, you may want to limit to only one transaction per user so that the order is maintained, but meanwhile allowing parallel processing of multiple users.
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.