In my project I have ConcurrentDictionary<int, SemaphoreSlim>
.
My application lookup already created SemaphoreSlim by key. If it's not exist - creates new one and put it into Dictionary.
Also at some point I make await of this semaphore and then release. After release semaphore aplication should decide to remove this semaphore from dictionary or not - just because there already can be another tread waiting for release this particular semaphore. I use this code:
semaphore.Release();
if(semaphore.CurrentCount == 0)
{
Dicitionary.TryRemove(key, out semaphore);
}
And here I get problem. At some point after Release()
semaphores CurrentCount
is 0, but when thread starts to remove it from dictionary - another thread awaits this semaphore.
In a result - semaphore was removed from dictionary and can't never be released (I use dictionary as storage).
Can someone suggest how to avoid such behavior.