Reputation: 372
In one thread (thread2) I have changed a value e.g.
CheckSuccess = false;
Now the main thread (thread1 - GUI / Form) does not pickup the change, how would it be possible to "propogate" the changes around all threads?
I was under the impression that threads should manipulate the data, not work on seperate instances (unless told to do so)
Upvotes: 2
Views: 3744
Reputation: 62439
The problem is most likely compiler optimizations causing the caching of the boolean value in a CPU register. Declaring it as volatile
should solve your problem.
Upvotes: 0
Reputation: 62504
It seems like a Race Condition. To avoid this you should synchronize an access to the shared variables.
volatile
keyword.If CheckSuccess
is a property (which will be translated to a method call) you can use lock() statement:
private static readonly object stateLock = new object();
lock (stateLock)
{
// access a shared variable here
CheckSuccess = false;
}
If CheckSuccess
is a property of UI control and you want changing it from a worker thread - you should use special techniques to push changes from a worker to the UI thread, it depends on which framework you are using WinForms of WPF.
PS: Also if you have multiple threads reading a value and few threads writing (basically reads more often than writing) you may find useful ReaderWriterLock
Upvotes: 3