Ive got a thread that does some work in the background and passes updates to the Form using the Invoke, BeginInvoke methods. The thread is created after the form is displayed so no issue there.
The issue is how to correctly shutdown. My worker thread has the ability to be asked to exit, and will exit some time soon after that (miliseconds).
However if the form has closed first the Invoke stuff breaks. I tried adding a Thread.Join to the forms closing event, but of course this causes a deadlock, even for BeginInvoke since somhow a Thread.Join blocks a BeginInvoke on that thread...
What is the correct way to close the form and shutdown its worker thread cleanly?
EDIT:
basic current code:
volatile bool abort;
void WorkerThread()
{
while(!abort)DoStuffIncludingInvokesOnThisForm();
}
void MyForm_FormClosing(object sender, FormClosingEventArgs e)
{
abort = true;
workerThread.Join();//will deadlock with DoStuffIncludingInvokesOnThisForm
//if get here before workerThread has exited, invokes will fail if workerthread is still in DoStuffIncludingInvokesOnThisForm
}