Async locking based on key
See original GitHub issueSometimes, I have situations where I want to lock certain areas for a particular user only (e.g. some business logic must be run in one piece for a certain user). I’m using neosmart AsyncLock in some software solutions and therefore - instead of inventing some new nugets - I was asking myself if it would be possible to extend AsyncLock.LockAsync
method with a key parameter.
using (await _lock.LockAsync(userId))
{
// Protected for User with userId
}
I’m not sure if you let other people touch your code (you know what I mean…) and I also have not a very clear picture of how I could integrate such a feature into AsyncLock. But I guess we could use some kind of thread-safe dictionary, which adds key-value pairs of T (generic-typed key) and value (the lock handle, some SemaphoreSlim or whatever you use in AsyncLock).
Let me know what you think about it.
Issue Analytics
- State:
- Created 2 years ago
- Comments:7 (4 by maintainers)
Top GitHub Comments
Note that
AsyncLock
andScopedMutex
are fundamentally different under the hood (one recurses, one doesn’t; one requires synchronization over a global dictionary, one doesn’t). AddingNeoSmart.Synchronization
will pull inNeoSmart.AsyncLock
so you don’t need to add both to your project, if you care about that.Yes, this is an extremely important type of locking to support, especially in contexts where idempotency is a must (e.g. when charging an order). I actually already published a nuget for just that when .NET Core was first introduced to work around the lack of named mutexes supporting
.WaitAsync()
.It’s part of the “NeoSmart Web Toolkit” available at https://github.com/neosmart/web and on NuGet as
NeoSmart.Web
. You wantNeoSmart.Web.ScopedMutex
(direct link to docs).I’m pretty sure this sample is exactly what you are looking for: