问题描述
限时送ChatGPT账号..这是我的两个方法变体,它返回一个与枚举值相关联的字符串(保存在字典中).第一个变体较慢,但线程安全,第二个变体更快,但我不知道它是否是线程安全的.第一:
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;
}
第二个变体:
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?
推荐答案
这里有两个问题:
lock (someDictionary)
- 不建议这样做,即使字典没有在其他地方使用.这是一个理论上的论点,但 Dictionary 类的(未来)代码可以锁定自身.
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))
没有锁.我假设这是对 TryGetValue()
的调用.这根本不是线程安全的,您的 Read 可能会被另一个线程中的 Write 中断.这可能以各种错误结束(索引超出范围,空引用).错误将非常罕见(= 难以重现).
if (!someDictionary (e, out str))
without a lock. I assume this is a call to TryGetValue()
. 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).
这篇关于这是否使用字典线程安全?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
更多推荐
[db:关键词]
发布评论