✅ Is it possible to lock method by id?
I don't know how to write correct question but I would try to describe my idea. Let's say I have this method:
public async Task<Dto> Modify(string groupId) => ..
Imagine there are 4 people inside 1 group and someone called Modify
method. Modification was started, it takes 1 minute for example and someone from this group called Modify
method again.
I want to deny the second user to use Modify
method because first user didn't get the response. How can I do it?19 Replies
You can use the TryEnter method on a monitor. If it failed, another thread is already entered
Yes, I know about
lock
but actually I don't need it.
Imagine we have 2 groups with people
so lock can't help meif someone is already modifying, do you want the second caller to wait, or fail?
you can have a lock for each group
named semaphore?
by the way I think lock and async things are not good things idk
i would use a
ConcurrentDictionary<groupId, object>
correcthm didn't think about it
maybe wait..
the async method can change threads, which could lead to problems with the lock
i dont know about that, youll have to do some research
Are you sure sharing something between multiple groups and locking only within those groups is the ideal scenario? What if you made an object for each group that they own?
It might be an XY problem
What about an
AsyncLocal<bool>
in the group object that keeps track of the state?for
lock
behaviour, as in waiting til u acquire the lock, i usually use a SemaphoreSlim
if i want to try to aquire a lock but otherwise fail, i usually use an int
and Interlocked.Exchange()
note that these ways of doing things arent safe for reentrantUse redis for distrubted lock
your keyword is "Distributed Locks"
i dont think thats needed
from a quick google, you should be fine with a
SemaphoreSlim.WaitAsync
u could also choose to use
dotNext.Threading
, it comes with a bunch of async friendly locks
AsyncExclusiveLock
(https://dotnet.github.io/dotNext/features/threading/exclusive.html) is just one among manyit will be fun if we can do this:
using @lock = lock;
would be cool but its not a good idea to abuse Dispose like that
hehe
now Enter and Exit should implement AcquireAsync from AsyncExclusiveLock
using
+ IDisposable
is quite often used for such stuff,
especially u see often some kind of lease struct for some array which simply returns the array to the poolit makes sense for something that acquires and releases yeah
thanks for helping