Right, my application occassionally kicks off a background thread that does some stuff.
As its doing its stuff it also updates a progress bar on the main window. It does this by calling Invoke to get the main thread to update the interface.
When the user closes the application, I want to wait until all the background threads are finished before closing the form. In the form closing event I have something like
while ( this._Queue.Count > 0 )
Application.DoEvents ();
But this does not work!!
The background thread is getting stuck on the Invoke call. The main thread continues to loop around calling its DoEvents, which I thought would be all it needed to do to pick up and process its invokes. But it isnt doing this…
Why not!?!
Right, I have sorted out the problem by taking it from a different angle. No more waiting for threads to finish…
I have just added a variable bool KillOnThreadFinish in the worker thread.
Then in the form closing of main form I check if the thread is running. If it is I set KillOnThreadFinish = true, I set e.cancel = true ( to prevent the form closing at that point ) and I set the MainForm.Enabled = false ( to prevent the user from closing the form again ).
Then when the thread finishes its work it checks KillOnThreadFinish and if True calls Application.Exit() and the app exits.
Seems to work beautifully!
(Thanks for trying guys. 🙂 )