For thread synchronization, it's recommended that you use one of the EventWaitHandle
classes, such as ManualResetEvent
. While it's marginally simpler to employ a simple boolean flag as you do here (and yes, you'd want to mark it as volatile
), IMO it's better to get into the practice of using the threading tools. For your purposes, you'd do something like this...
private System.Threading.ManualResetEvent threadStop;void StartThread(){ // do your setup // instantiate it unset threadStop = new System.Threading.ManualResetEvent(false); // start the thread}
In your thread..
while(!threadStop.WaitOne(0) && !operationComplete){ // work}
Then in the GUI to cancel...
threadStop.Set();