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.
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.
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.
The function itself still is thread safe, as long as it does not contain any self-modfying code.
Each thread will share the same static variable which is mostly likely a global variable.
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 love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With