Here is two my variants of method, which returns a string, associated with enum value (kept in dictionary). First variant is slower, but thread-safe, second is faster, but i don’t know, whether it is thread-safe or not. First:
string GetStringForEnum (SomeEnum e)
{
string str = null;
lock (someDictionary) //someDictionary is not used anywhere else (only in this method)
{ if (!someDictionary (e, out str)) { someDictionary.Add (e, "somehowCreatedString"); }
return str;
}
Second variant:
string GetStringForEnum (SomeEnum e)
{
string str = null;
if (!someDictionary (e, out str))
{
lock (someDictionary) //someDictionary is not used anywhere else (only in this method)
{ if (!someDictionary (e, out str)) { someDictionary.Add (e, "somehowCreatedString"); }
}
return str;
}
Second variant is not used “lock” each time, but is it thread-safe or not?
There are 2 problems here:
lock (someDictionary)– this is dis-advised, even if the dictionary is not used elsewhere. It is a theoretical argument but the (future) code of the Dictionary class could lock on itself.if (!someDictionary (e, out str))without a lock. I assume this is a call toTryGetValue(). This simply is not thread-safe, your Read could be interrupted by a Write in another thread. This could end in all sorts of errors (index out of range, null reference). The errors will be very rare (= hard to reproduce).