Reputation: 2552
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.
Upvotes: 8
Views: 1221
Reputation: 444
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
Upvotes: 0
Reputation: 273824
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.
Upvotes: 13