.NET - Dictionary locking vs. ConcurrentDictionary

2019-01-04 17:10发布

I couldn't find enough information on ConcurrentDictionary types, so I thought I'd ask about it here.

Currently, I use a Dictionary to hold all users that is accessed constantly by multiple threads (from a thread pool, so no exact amount of threads), and it has synchronized access.

I recently found out that there was a set of thread-safe collections in .NET 4.0, and it seems to be very pleasing. I was wondering, what would be the 'more efficient and easier to manage' option, as i have the option between having a normal Dictionary with synchronized access, or have a ConcurrentDictionary which is already thread-safe.

Reference to .NET 4.0's ConcurrentDictionary

8条回答
淡お忘
2楼-- · 2019-01-04 18:12

Have you seen the Reactive Extensions for .Net 3.5sp1. According to Jon Skeet, they have backported a bundle of the parallel extensions and concurrent data structures for .Net3.5 sp1.

There is a set of samples for .Net 4 Beta 2, which describes in pretty good detail on how to use them the parallel extensions.

I've just spent the last week testing the ConcurrentDictionary using 32 threads to perform I/O. It seems to work as advertised, which would indicate a tremendous amount of testing has been put into it.

Edit: .NET 4 ConcurrentDictionary and patterns.

Microsoft have released a pdf called Patterns of Paralell Programming. Its reallly worth downloading as it described in really nice details the right patterns to use for .Net 4 Concurrent extensions and the anti patterns to avoid. Here it is.

查看更多
倾城 Initia
3楼-- · 2019-01-04 18:13

We've used ConcurrentDictionary for cached collection, that is re-populated every 1 hour and then read by multiple client threads, similar to the solution for the Is this example thread safe? question.

We found, that changing it to ReadOnlyDictionary improved overall performance.

查看更多
登录 后发表回答