Currently I use this class (got it from here):
public static class IntSynchronizer
{
private static readonly ConcurrentDictionary<int, object> locks;
static IntSynchronizer()
{
locks = new ConcurrentDictionary<int, object>();
}
public static object GetLock(int id)
{
return locks.GetOrAdd(id, new object());
}
}
And then I use it like
lock (IntSynchronizer.GetLock(clientId))
{
// do stuff (nothing async) that can only be done once per client at any given moment
}
And that works, but apparently you can't use this if you need to make async calls.
So then I found this other way, like this:
private static readonly SemaphoreSlim _someLock = new (1,1);
And then I use that like this
await _someLock.WaitAsync();
try
{
// do async things that can only be done one at a time
}
finally
{
_someLock.Release();
}
I need to combine these things. How do I lock on an integer like in the first example, but support async calls, like in the second example?