.NET has introduced a thread safe dictionary (4.0 onward). Essentially, it does something similar like conventional dictionary plus lock system. Read the MSDN documentation for the same at following link:
http://msdn.microsoft.com/en-us/library/ee378677(v=vs.110).aspx
The .NET implementation of dictionary has only caveat, it doesn't guarantee of insertion of element, if traffic is heavy. Following is MSDN remarks in this context
If you call GetOrAdd simultaneously on
different threads, addValueFactory may
be called multiple times, but its
key/value pair might not be added to
the dictionary for every call.
We should still use .NET version of thread safe dictionary (known as ConcurrentDictionary) due to two reasons:
- It is apparently fast for most common scenarios (especially when read is dominating write)
- Our code readability will improve significantly (by avoiding lock code overhead)
What does this mean to you in term of action items?
- Start using ConcurrentDictionary now onward in place of regular Dictionary
- Replace all regular Dictionary (with or without lock) objects with ConcurrentDictionary
How do we mitigate the known caveat with ConcurrentDictionary?
Avoid using the dictionary value immediately after assigning the value. See the following example for the same.
Wrong:
static ConcurrentDictionary<int, string> userIDNameMap = new ConcurrentDictionary<int, string>();
public string GetUserName(int id)
{
if (!userIDNameMap.ContainsKey(id))
{
userIDNameMap[id] = GetUserNameFromDB(id);
}
return userIDNameMap[id]; //Remember concurrent dictionary does not guarantee addition of the object
}
Right:
static ConcurrentDictionary<int, string> userIDNameMap = new ConcurrentDictionary<int, string>();
public string GetUserName(int id)
{
string userName = string.Empty;
if (userIDNameMap.ContainsKey(id))
{
userName = userIDNameMap[id];
}
else
{
userName = GetUserNameFromDB(id);
userIDNameMap[id] = userName;
}
return userName;
}
0 Comment(s)