0

I have a window that receives asynchronous events from a worker thread. Sometimes these events come in after the window is closed and when I call Invoke() to process the event, I get an exception.

How can I test to make sure the window is still good. Or to cause all events to be processed somewhere in the closing lifecycle?

thanks - dave

Reza Aghaei
  • 120,393
  • 18
  • 203
  • 398
David Thielen
  • 28,723
  • 34
  • 119
  • 193
  • It is an inevitable threading race. You can check that it is not disposed yet with its IsDisposed property, but then it may get disposed between the test and the Invoke call. Small odds, not zero. You have to ensure that this cannot happen and that the thread is stopped or completed before you allow the form to close. This does require that you cancel the close since you don't control the user either. https://stackoverflow.com/a/1732361/17034 – Hans Passant Mar 25 '18 at 19:17

1 Answers1

0

You can check IsHandleCreated before calling invoke, to make sure the form is created and is not destroyed:

if (this.IsHandleCreated)
{
    //this.Invoke ...
}

The property returns false if the form handle is still not created or it has destroyed after closing the form. It also prevents the error of calling invoke before showing the form and before the handle is created.

If for any reason you just care about closing the form, you can check IsDisposed property.

Reza Aghaei
  • 120,393
  • 18
  • 203
  • 398