Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to wait until a value becomes added to ConcurrentDictionary or timeout occurs?

I have a task that should wait until a value has been added to a ConcurrentDictionary. If the value is added, it should stop waiting and continue its work. It should stop waiting as well if a timeout occured (5 seconds for example).

The value should be added to the ConcurrentDictionary by another thread/task, however, due to the nature of the code, I do not want the threads to communicate with each other.

How I should go about implementing this (in C#) ?

Btw I am using Tasks, not Threads for most of the part, and thus I am not sure if Thread.Sleep or other methods on the current Thread would be a good decision, cause it might sleep other tasks which use the same thread and cause random problems.

like image 769
xander Avatar asked Nov 03 '22 05:11

xander


1 Answers

I think "waiting" for an element to be added to a collection is generally a bad thing. Doing this, in general, means that a thread is blocked for some period of time. If it's even possible, you then have to deal with timeouts. If it's not possible to detect timeouts then you have to deal with aborting the thread to abort the wait (you never want to get into a situation where a thread is blocked indefinitely) e.g. cancellation.

ConcurrentDictionary is thread safe in and of itself; but this doesn't make all code that uses ConcurrentDictionary thread safe. The application-specific thread-safety requirements need to still be taken into account when using a ConcurrentDictionary object. ConcurrentDictionary cannot possibly implement those types of things. What to do when a value is added to the dictionary is also very similar--the overhead of waiting or notifying external code upon new value additions would cause all usages of ConcurrentDictionary to be slower, even those usages that don't need to wait or don't need to be notified--so things like that are not implemented. The fact that an application adds a value and needs to be notified that a value was added is probably pretty rare (from the dictionaries point of view, why would it tell you that you just added a value...). So, that sort of application-specific thing is normally done at the application level. i.e. the fact that a concurrent dictionary is used is a coincidence and your application notifies other threads that another thread has done something they need to know about. This could mean wrapping adds to a dictionary instance with calls to ManualResetEventSlim.Reset/Set and something can wait with a ManualResetEventSlim.Wait override. Or, it could simply be a matter of writing an event that gets raised whenever a value is added to the dictionary.

like image 192
Peter Ritchie Avatar answered Nov 09 '22 11:11

Peter Ritchie