采用以下代码,在多线程环境中会发生什么:
static Dictionary<string,string> _events = new Dictionary<string,string>();
public static Dictionary<string,string> Events { get { return _events;} }
public static void ResetDictionary()
{
_events = new Dictionary<string,string>();
}
在多线程环境中,不同线程可以同时访问此方法和属性。
将新对象分配给可在不同线程中访问的静态变量是否是线程安全的?会出现什么问题?
是否存在事件可以为空的时刻?例如,如果 2 个线程同时调用 Events
和 ResetDictionary()
。
最佳答案
Is it thread safe to assign a new object to a static variable that is accessible in different threads?
基本上,是的。从某种意义上说,该属性永远不会无效或 null
。
What can go wrong ?
一个阅读线程可以在另一个线程重置旧字典后继续使用它。这有多糟糕完全取决于您的程序逻辑和要求。
关于c# - 在c#中为静态对象分配一个新值是否线程安全,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18273004/