WinForms multithreading issue

I have a thread that does some work in the background and passes updates to the form using Invoke, BeginInvoke methods. The stream is created after the form is displayed, so there is no problem.

The problem is how to shut down properly. My working thread has the ability to ask to exit and will soon come out after a while (miliseconds).

However, if the form is closed, the Invoke material first unfolds. I tried adding Thread.Join to the form closing event, but of course this causes a deadlock, even for BeginInvoke, since Thread.Join has since blocked BeginInvoke in this thread ...

What is the correct way to close a form and completely close a workflow?

EDIT:

base 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 } 
+4
source share
2 answers

Add a handler for FormClosing and ask your thread to exit nicely ...

+1
source

From the Form.Closing event Form.Closing set the Cancel property to true to temporarily delay closing the form until the workflow completes. After the workflow is completed, you can reissue the Close command on the form.

 public class MyForm : Form { private volatile bool abort = false; private bool IsCloseRequested = false; private bool IsWorkerThreadComplete = false; private void MyForm_Closing(object sender, FormClosingEventArgs args) { if (!IsWorkerThreadComplete) { args.Cancel = true; IsCloseRequested = true; abort = true; } } void WorkerThread() { try { while (!abort) DoStuffIncludingInvokesOnThisForm(); } finally { OnWorkerThreadComplete(); } } private void OnWorkerThreadComplete() { if (InvokeRequired) { Invoke(((MethodInvoker)() => OnWorkerThreadComplete), null); } else { IsWorkerThreadComplete = true; if (IsCloseRequested) Close(); } } } 
+1
source

All Articles