2

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)

sll
  • 61,540
  • 22
  • 104
  • 156
James Teare
  • 372
  • 1
  • 12
  • 23

3 Answers3

3

It seems like a Race Condition. To avoid this you should synchronize an access to the shared variables.

  • If CheckSuccess is a field - try out marking it by 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

Community
  • 1
  • 1
sll
  • 61,540
  • 22
  • 104
  • 156
  • It won't solve the race condition, since it's just about writing an atomic value. Just incorrect order of execution. – Dykam Dec 17 '11 at 13:32
  • @Dykam : I believe CheckSuccess is a property which translated to a method call, but need to clarify perhaps this is bad naming for a field – sll Dec 17 '11 at 13:37
0

I normally use Interlocked methods such as Exchange. This is much simpler than using a locking object and it's guaranteed to be atomic.

Strillo
  • 2,952
  • 13
  • 15
0

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.

Tudor
  • 61,523
  • 12
  • 102
  • 142