简体   繁体   中英

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.

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 .

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! see the link: Cleanest Way to Invoke Cross-Thread Events

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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