Common variables between stream and C # UI

Is it possible to safely exchange this "status" between two threads?

private bool status = false; private void uiNewThread_bootloaderStartIdSetupAuto() { while (status) ; } 

Below is a new thread that will be launched from the user interface below:

  private void uiBtnBootloaderStartIdSetupAuto_Click(object sender, EventArgs e) { if (MessageBox.Show("ID will be setup starting from 1 to 16. \n\nAfter pressing 'YES', press the orange button one-by-one on the nodes.\nThe first pressed node will have number 1, the next number 2, and so on... \n\nWhen done, hit DONE button.", "ID setup", MessageBoxButtons.YesNo) == DialogResult.Yes) { status = true; Thread transmitConfig = new Thread(new ThreadStart(uiNewThread_bootloaderStartIdSetupAuto)); //close port in new thread to avoid transmitConfig.Start(); } else { Log(LogMsgType.Normal, "User cancelled"); status = false; } } 
+4
source share
2 answers

Optimizations such as caching or reordering performed by the compiler or processor can damage your code. You must declare a volatile field to prevent this:

 private volatile bool status = false; 

An example of what might go wrong is that if two threads are running on different cores, the status value can be cached in the CPU register using the kernel in which the polling thread runs, therefore, never seeing the value is updated by another branch.

Try creating the application in Release mode and you will see this effect.

+4
source

You might be better off just locking the variable, for example.

 private static readonly object _lock = new Object(); .... lock(_lock){ //access to boolean variable etc. } 

Another possibility is to wrap the bool in Lazy, and accessing the internal value is a safe thread.

If you want to use locking mechanisms to read and update values, you might consider using methods from the Interlocked class.

Information here:

System.Threading.Interlocked

0
source

All Articles