Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/315.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 在c中为静态对象指定一个新值是线程安全的吗#_C#_Thread Safety - Fatal编程技术网

C# 在c中为静态对象指定一个新值是线程安全的吗#

C# 在c中为静态对象指定一个新值是线程安全的吗#,c#,thread-safety,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

通过以下代码,了解在多线程环境中发生的情况:

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>();
}
static Dictionary\u events=new Dictionary();
公共静态字典事件{get{return\u Events;}}
公共静态void ResetDictionary()
{
_事件=新字典();
}
在多线程环境中,不同线程可以同时访问此方法和属性

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

是否有一个事件可以为空的时刻??例如,如果两个线程同时调用
事件
ResetDictionary()

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

基本上,是的。从某种意义上说,属性永远不会无效或
null

什么会出错


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

如果您想控制多线程环境中的所有内容,您必须使用所有线程都可以访问的标志,并控制字典中使用的方法

// the dictionary
static Dictionary<string, string> _events = new Dictionary<string, string>();

// public boolean
static bool isIdle = true;

// metod that a thread calls
bool doSomthingToDictionary()
{
    // if another thread is using this method do nothing,
    // just return false. (the thread will get false and try another time!)
    if (!isIdle) return false;

    // if it is Idle then:
    isIdle = false;
    ResetDictionary(); // do anything to your dictionary here
    isIdle = true;
    return true;
}
//字典
静态字典_events=新字典();
//公共布尔
静态布尔isIdle=真;
//我知道线程调用
bool doSomthingToDictionary()
{
//如果另一个线程正在使用此方法,则不执行任何操作,
//只需返回false。(线程将变为false并重试!)
如果(!isIdle)返回false;
//如果它处于空闲状态,则:
isIdle=假;
ResetDictionary();//在这里对您的字典做任何操作
isIdle=true;
返回true;
}
还有一件事!您可以使用Invoke方法来确保当一个线程在另一个线程中操作变量或调用函数时,其他线程不会!请参阅链接:

如果两个线程同时调用
事件
重置字典
,那么可能发生的情况是:线程1处理
事件
事件
最终成为一个空字典,或者线程2首先调用
重置字典
,然后线程2对其进行处理<代码>事件不会以
null
结束,除非它被另一个线程特别设置为
null
;当线程检查
Events!=在另一个调用
ResetDictionary
之前,null
。如果您希望变量值不会更改(对于每个请求类似),或者即使更改也不会影响您的应用程序(但会影响),请使用静态变量,有可能你的应用程序将运行在错误的逻辑上,它甚至不会引发任何异常,考虑用户改变任何值,然后每一个其他传入请求处理错误数据,直到该值被其他逻辑重置。因此,明智地使用静态变量。