这是否使用字典线程安全?

编程入门 行业动态 更新时间:2024-10-25 04:24:20
本文介绍了这是否使用字典线程安全?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时送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:关键词]

本文发布于:2023-04-30 16:25:58,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1396281.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:这是   线程   字典

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!