Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

A .Net4 Gem: The ConcurrentDictionary - Tips & Tricks

I started to use the new ConcurrentDictionary from .Net4 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?

like image 665
SDReyes Avatar asked Apr 20 '10 19:04

SDReyes


1 Answers

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

like image 187
Joe Avatar answered Sep 17 '22 15:09

Joe