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?
W开发者_StackOverflow社区hat 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).
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.
ConcurrentDictionary is thread-safe. You do not have to worry about it even when using it from multiple threads.
精彩评论