Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How ConcurrentDictionary is accessed and how to serialize it?

I've never used the ConcurrentDictionary object before and have a couple questions about it:

  1. Am I correct that multiple threads can read from the dictionary at the same time, but if it's being written to, no other thread can access it?

  2. Can this object be serialized to disk?

Thanks.

like image 277
Randy Minder Avatar asked Sep 21 '11 22:09

Randy Minder


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 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.

What is the purpose of the ConcurrentDictionary TKey TValue class in C#?

ConcurrentDictionary<TKey, TValue> Class Represents a thread-safe collection of key-value pairs that can be accessed by multiple threads concurrently.


2 Answers

Am I correct that multiple threads can read from the dictionary at the same time, but if it's being written to, no other thread can access it?

No, you can safely read and write from multiple threads. Of course internally I suppose that there is some synchronization happening but the performance penalty should be small and you shouldn't be worried about it and do any additional synchronization.

Can this object be serialized to disk?

Depends on what serializer you use.

  • JavaScriptSerializer: yes
  • Json.NET: yes
  • DataContractSerializer: yes
  • BinaryFormatter: yes
  • XmlSerializer: no (well, you could do some hacking to make it work but it will be a PITA => XmlSerializer is allergic to the IDictionary<TKey, TValue> interface)
like image 195
Darin Dimitrov Avatar answered Oct 09 '22 15:10

Darin Dimitrov


  1. Am I correct that multiple threads can read from the dictionary at the same time, but if it's being written to, no other thread can access it?

This is not observable, you can read and write from multiple threads and let the class worry about the synchronization.

  1. Can this object be serialized to disk?

Yes, it is marked with [Serializable]. And you can always extract the <K,V> pairs and use any Serializer you like.

like image 3
Henk Holterman Avatar answered Oct 09 '22 16:10

Henk Holterman