views:

498

answers:

3

Hi guys,

I started to use the new ConcurrentDictionary from .Net4 yesterday to implement a simple caching for a threading project.

But I'm wondering what I have to take care of/be careful about when using it?

What have been your experiences using it?

A: 

ConcurrentDictionary is thread-safe. You do not have to worry about it even when using it from multiple threads.

Tom Cabanski
+2  A: 

I have had no issues with the Concurrent collection objects so far. They are a huge boost to my productivity by allowing me to not worry about concurrency issues with the collections and focus on writing application logic.

This is not to say there are no issues. Just nothing I've run into.

ChaosPandion
Thank you Chaos +1
SDReyes
+14  A: 

Members are thread-safe, but you shouldn't expect a sequence of calls to be thread-safe. For example you can't expect the following to be thread-safe:

if (!dictionary.ContainsKey(key))
{
    // Another thread may have beaten you to it
    dictionary.Add(key, value);
}

Instead, use the new thread-safe API - e.g. AddOrUpdate (last one wins in the event of a race condition) or GetOrAdd (first one wins in the event of a race condition).

Joe
Very useful Joe Thanks! +1
SDReyes
This is a far better answer than the accepted answer.
Martin
I'm going to wait for more responses now, Martin. Thanks : )
SDReyes
@Martin - I agree. :)
ChaosPandion
Note that the MS documentation says here: http://msdn.microsoft.com/en-us/library/dd997369.aspx that GetOrAdd and AddOrUpdate may not return the same item that you inserted. I believe this is just for the Function<> variant of the methods but the writing is ambiguous.
evilfred
@evilfred, this does apply to the Func<> variant - the description makes this clear. The Func<> variant essentially allows you to create a lazy-loaded dictionary, and in practice I'd expect all threads to be using the same delegate, and that the result returned by multiple invocations of the delegate are interchangeable (e.g. immutable).
Joe