简体   繁体   English

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

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

Taking the following code, what happens in a multithreaded environment: 采用以下代码,在多线程环境中会发生什么:

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>();
}

In a multithreaded environment this method and property can be accessed in the same time by different threads. 在多线程环境中,可以通过不同的线程同时访问此方法和属性。

Is it thread safe to assign a new object to a static variable that is accessible in different threads? 将新对象分配给可在不同线程中访问的静态变量是否安全? What can go wrong ? 什么可能出错?

Is there a moment in time when Events can be null ?? 有什么时候事件可以为空吗? If 2 threads call in the same time Events and ResetDictionary() for example. 如果2个线程同时调用EventsResetDictionary()

Is it thread safe to assign a new object to a static variable that is accessible in different threads? 将新对象分配给可在不同线程中访问的静态变量是否安全?

Basically, yes. 基本上,是的。 In the sense that the property will never be invalid or null . 从某种意义上说,该属性永远不会无效或为null

What can go wrong ? 什么可能出错?

A reading thread can continue to use the old dictionary after another thread has reset it. 另一个线程重置后,读取线程可以继续使用旧字典。 How bad this is depends entirely on your program logic and requirements. 这有多糟糕取决于您的程序逻辑和要求。

if you want to control everything in a multi-threading environment you have to use a flag that is accessible by all the treads and control the methods you use on your dictionary! 如果你想控制多线程环境中的所有内容,你必须使用所有踏板都可以访问的标志,并控制你在字典上使用的方法!

// 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;
}

another thing! 另一件事! you can use the Invoke method to be sure that when one thread is manipulating a variable or calling a function in another thread, other threads will not! 您可以使用Invoke方法确保当一个线程正在操作变量或在另一个线程中调用函数时,其他线程将不会! see the link: Cleanest Way to Invoke Cross-Thread Events 请参阅链接: 调用跨线程事件的最简洁方法

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

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