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?
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With