Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Concurrent Dictionary in C#

Tags:

c#

.net

I need to implement concurrent Dictionary because .Net does not contain concurrent implementation for collections(Since .NET4 will be contains). Can I use for it "Power Threading Library" from Jeffrey Richter or present implemented variants or any advice for implemented? Thanks ...

like image 507
jitm Avatar asked Mar 25 '10 12:03

jitm


People also ask

What is concurrent dictionary?

adjective. occurring or existing simultaneously or side by side: concurrent attacks by land, sea, and air. acting in conjunction; cooperating: the concurrent efforts of several legislators to pass the new law. having equal authority or jurisdiction: two concurrent courts of law.

What is the purpose of concurrent dictionary?

ConcurrentDictionary<TKey,TValue> provides several convenience methods that make it unnecessary for code to first check whether a key exists before it attempts to add or remove data. The following table lists these convenience methods and describes when to use them.

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

Represents a thread-safe collection of key/value pairs that can be accessed by multiple threads concurrently.

Is ConcurrentDictionary keys thread-safe?

ConcurrentDictionary Represents a thread-safe collection of key-value pairs that can be accessed by multiple threads concurrently.


2 Answers

I wrote a thread-safe wrapper for the normal Dictionary class that uses Interlocked to protect the internal dictionary. Interlocked is by far the fastest locking mechanism available and will give much better performance than ReaderWriterLockSlim, Monitor or any of the other available locks.

The code was used to implement a Cache class for Fasterflect, which is a library to speed up reflection. As such we tried a number of different approaches in order to find the fastest possible solution. Interestingly, the new concurrent collections in .NET 4 are noticeably faster than my implementation, although both are pretty darn fast compared to solutions using a less performance locking mechanism. The implementation for .NET 3.5 is located inside a conditional region in the bottom half of the file.

like image 182
Morten Mertner Avatar answered Oct 19 '22 22:10

Morten Mertner


You can use Reflector to view the source code of the concurrent implementation of .NET 4.0 RC and copy it to your own code. This way you will have the least problems when migrating to .NET 4.0.

like image 45
Steven Avatar answered Oct 19 '22 22:10

Steven