I have an ASP .net core API that invites guests to an event. The primary problem was that if two individuals used this same API at the same time on the same event and invited the same people, it was allowing it. After asking someone that is a JAVA developer, he informed me that they have a term called Synchronized
, therefore I decided to look for the c# counterpart.
Initially, I discovered [MethodImpl(MethodImplOptions.Synchronized)]
and the lock
keyword, and began utilizing it to encapsulate my API. It worked fine and only allowed one person to use the API concurrently, but then I decided to add async capabilities to my API to make it quicker and not block the UI, and here is when I learned that I couldn't utilize both synchronized and lock with async.
I discovered SemaphoreSlim
and its .WaitAsync();
and .Release();
keywords after doing some research. I tested it, and it worked as expected, but one thing bothered me: blocking an entire API because someone wants to add to a particular event does not seem sensible. For example, if person1 is using the API to invite people to event(A) while another person, person2 is attempting to invite people to event(B), it is illogical to block person2 from inviting to event(B), because person1 is holding the semaphore keys.
My Problem: Is there a way to use sempahoreslim or another realistic method to define a semaphoreslim key per event id rather than define a semaphore key to have just one key per API? I discovered this code after doing some research. I tested it and it worked, however my problem is that he does not remove the object from the dictionary when he is through. I want to delete it after the API has completed its work on that event. I understand how to delete stuff from dictionaries by key. But is there a better way than utilizing dictionaries to do what I'm attempting?