Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cast from ConcurrentDictionary to IDictionary

Does a cast from ConcurrentDictionary to IDictionary cut off the thread-safe implementation, since IDictionary doesn't have GetOrAdd and AddOrUpdate methods ?

like image 577
Luciano Avatar asked Apr 11 '12 18:04

Luciano


People also ask

How do you find the value of ConcurrentDictionary?

To retrieve single item, ConcurrentDictionary provides TryGetValue method. We have to provide Key in the TryGetValue method. It takes the out parameter to return the value of key. TryGetValue returns true if key exists, or returns false if key does not exists in dictionary.

Is ConcurrentDictionary AddOrUpdate thread-safe?

It is thread safe in your usage. It becomes not thread safe when the delegate passed to AddOrUpdate has side effects, because those side effects may be executed twice for the same key and existing value.

Is ConcurrentDictionary ordered?

No. The list order of ConcurrentDictionary is NOT guaranteed, lines can come out in any order.

Is ConcurrentDictionary thread-safe C#?

Concurrent. ConcurrentDictionary<TKey,TValue>. This collection class is a thread-safe implementation. We recommend that you use it whenever multiple threads might be attempting to access the elements concurrently.


1 Answers

The resulting object will still be a concurrent dictionary. The calls like Add or Remove use the underlying implementation TryAdd and TryRemove (which are thread-safe). Casting an object to a different type doesn't change the object itself.

Also, for clarification, you could use tools like ILSpy to see what's the implementation of default IDictionary methods and whether they'll be still thread-safe.

like image 163
Dmitry Reznik Avatar answered Oct 04 '22 05:10

Dmitry Reznik