Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 371
Dorin Avatar asked Aug 16 '13 12:08

Dorin


People also ask

Are static objects thread safe?

Thread Safety Static variables are not thread safe. Instance variables do not require thread synchronization unless shared among threads. But, static variables are always shared by all the threads in the process.

Can we assign value to static variable in C?

When static keyword is used, variable or data members or functions can not be modified again. It is allocated for the lifetime of program. Static functions can be called directly by using class name.

Are static functions thread safe in C?

The function itself still is thread safe, as long as it does not contain any self-modfying code.

Do threads share static variables in C?

Each thread will share the same static variable which is mostly likely a global variable.


1 Answers

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.

like image 162
Henk Holterman Avatar answered Oct 23 '22 22:10

Henk Holterman