开发者

Concurrent Dictionary in C#

开发者 https://www.devze.com 2022-12-24 20:05 出处:网络
I need to implement concurrent Dictionary because .Net does not contain concurrent implementation for 开发者_C百科collections(Since .NET4 will be contains). Can I use for it \"Power Threading Library\

I need to implement concurrent Dictionary because .Net does not contain concurrent implementation for 开发者_C百科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 ...


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.


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.


I wrote a concurrent dictionary myself (prior to .NET 4.0's System.Collections.Concurrent namespace); there's not much to it. You basically just want to make sure certain methods are not getting called at the same time, e.g., Contains and Remove or something like that.

What I did was to use a ReaderWriterLock (in .NET 3.5 and above, you could go with ReaderWriterLockSlim) and call AcquireReaderLock for all "read" operations (like this[TKey], ContainsKey, etc.) and AcquireWriterLock for all "write" operations (like this[TKey] = value, Add, Remove, etc.). Be sure to wrap any calls of this sort in a try/finally block, releasing the lock in the finally.

It's also a good idea to modify the behavior of GetEnumerator slightly: rather than enumerate over the existing collection, make a copy of it and allow enumeration over that. Otherwise you'll face potential deadlocks.


Here's a simple implementation that uses sane locking (though Interlocked would likely be faster): http://www.tech.windowsapplication1.com/content/the-synchronized-dictionarytkey-tvalue

Essentially, just create a Dictionary wrapper/decorator and synchronize access to any read/write actions.

When you switch to .Net 4.0, just replace all of your overloads with delegated calls to the underlying ConcurrentDictionary.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号