I have an annoying race condition when exiting my app Windows Forms application. While running, I have to poll a hardware device encapsulated by an Active X control:
while(!pollingThreadStop)
{
//get the current status
x = axFoo-> GetStatus();
//do something
}
pollingThreadStopped=true;
In the Form's closing event I try to detect that the user is exiting and stop the thread:
private: System::Void Form1_Closing( Object^ sender, System::ComponentModel::CancelEventArgs^ e )
{
pollingThreadStop=true;
while(!pollingThreadStopped)
Sleep(10);
}
Unfortunately, this seems to trigger a race condition where axFoo can begin shutting down before the Closing event is triggered, I suppose because the ActiveX control knows the window is being closed (?), in which case it sometimes deadlocks on the call to GetStatus because the hardware is already offline. Is there some way I can detect that the user has tried to close the Window earlier in the process so that I can quit the polling thread in time? Adding a GUI button that turns off the polling and then closes does work, but I'd really rather not have to do that.