is it thread safe to assign a new value to a static object in c#
c#, thread-safety
Solution
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.
Problem
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.