是否可以在c#中为静态对象赋值新的线程安全

Dor*_*rin 8 c# thread-safety

采用以下代码,在多线程环境中会发生什么:

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>();
}
Run Code Online (Sandbox Code Playgroud)

在多线程环境中,可以通过不同的线程同时访问此方法和属性.

将新对象分配给可在不同线程中访问的静态变量是否安全?什么可能出错?

有什么时候事件可以为空吗?如果2个线程调用的同时Events,并ResetDictionary()为例子.

Hen*_*man 13

将新对象分配给可在不同线程中访问的静态变量是否安全?

基本上,是的.从某种意义上说,财产永远不会无效或null.

什么可能出错?

另一个线程重置后,读取线程可以继续使用旧字典.这有多糟糕取决于您的程序逻辑和要求.