繁体   English   中英

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

[英]is it thread safe to assign a new value to a static object in c#

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

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个线程同时调用EventsResetDictionary()

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

基本上,是的。 从某种意义上说,该属性永远不会无效或为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;
}

另一件事! 您可以使用Invoke方法确保当一个线程正在操作变量或在另一个线程中调用函数时,其他线程将不会! 请参阅链接: 调用跨线程事件的最简洁方法

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM