这是我的两个方法变体,它返回一个字符串,与枚举值相关联(保存在字典中)。第一个变体较慢,但线程安全,第二个变体更快,但我不知道它是否是线程安全的。第一的:
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;
}
第二种变体:
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;
}
第二种变体不是每次都使用“锁”,但它是否是线程安全的?