I am new to writing multi-threaded code and am working on a Windows forms MDI application. There is an MDI Form that can have 0 to many MDI Children. The MDI form starts a thread that is used to poll a device via a USB port. When new data is available from the device, the thread raises an event that the child forms can subscribe to.
The event handlers in the child forms update themselves based on the new data that has arrived from the device. Since the event handler is called from the communication thread and not the UI thread, the code that updates the form must be "Invoked".
In the FormClosing event of the child form, I unsubscribe to the event before the form closes. But I often get an error because the communication event handler in the child form is getting called after the form has closed and been disposed.
I put a bunch of trace statements in to figure out what was going on and found that with several forms subscribed to the the event, the events could get queued up but I am able to close one of the forms before its event handler had been called. The form closing event occurs, the event handler is unsubscribed and the form is closed. However since the event handler has already been queued, the CLR (?) attempts to call the event handler on the disposed form.
I'm sure this is a common issue but I haven't been able to find an answer so far.