1

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.

Alexei Malashkevich
  • 1,575
  • 1
  • 17
  • 34
  • You are asking for a threading race bug. You have to deal with the cold hard fact, you can only ever remove the semaphore when you *know* that the thread(s) stopped running. If you don't know then you need to fix *that* problem. – Hans Passant Oct 19 '16 at 12:41
  • @HansPassant but actually the problem is that there is no way to know that threads stop using this semaphore. One thing I can only imagine - is to somehow mark semaphore that it's will be deleted and on await check every time this mark. – Alexei Malashkevich Oct 19 '16 at 12:49
  • I can't guess why you can't know, the BackgroundWorker and the Task classes make it particularly easy to know when a thread doesn't require a resource anymore because it completed. It is not the only detail that matters, if you don't know when a thread completes then you also don't know that it failed to get its job done. And you can't even know when it is safe to exit your program. Such a program is drastically unreliable. – Hans Passant Oct 19 '16 at 13:08
  • @AlexeiMalashkevich: Why are you removing the semaphores at all? – Stephen Cleary Oct 19 '16 at 13:22
  • @StephenCleary actually I aslo thought about not delete semaphores. But... actually it seems wrong, doesn't it? – Alexei Malashkevich Oct 19 '16 at 14:12
  • @AlexeiMalashkevich: Depends on what the "id" is. From your use case, it sounds like you can't know when an id is "done". – Stephen Cleary Oct 19 '16 at 15:02

0 Answers0