简体   繁体   中英

Closing Form from inside an Invoke

Closing a form from inside an Invoke like this:

Invoke(new Action(() => {
    Close();
    MessageBox.Show("closed in invoke from another thread");
    new Form1();
}));

throws an exception as soon as the form is closed:

Invoke or BeginInvoke cannot be called on a control until the window handle has been created.

But only on NET 4.0. On NET 4.5 no exceptions are thrown.

Is this expected behavior? How should I go about it?

If you start a thread during initialisation, you do not know how far the initialisation has gone in another thread.

You notice differences in behavior on different .Net versions, but you cannot be sure about the order of things on different machines.

I have solved a lot of threading issues in Windows forms using my own messagepump, using a Queue and a normal Timer control:

  • Add a timer control to your form, with a small interval (250 ms)
  • Add a Queue to your form.
  • Let the timer event dequeue the actions, and execute it.
  • Add Actions to the queue during initialisation or even other background jobs.

Using this approach will issues with background jobs during initialisation, but also during closing/disposing of the form, since the timer will only trigger if the form is fully functional.

That's because Close method closes the form and destroys it's handle and then the MessageBox is invoked in the Closed form with no handle, so the error message shows up.

I don't understand your purpose, but you should either move the code after Close out of invoke, or move the Close after them. For example:

Invoke(new Action(() => {
    Hide();
    MessageBox.Show("closed in invoke from another thread");
    new Form1();
    Close();
}));

Edit:

MSDN note about Control.Invoke :

The Invoke method searches up the control's parent chain until it finds a control or form that has a window handle if the current control's underlying window handle does not exist yet. If no appropriate handle can be found, the Invoke method will throw an exception. Exceptions that are raised during the call will be propagated back to the caller.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM