Exceptions on frame closing, funky workaround

intx13

Member
Joined
Jun 21, 2006
Messages
7
Programming Experience
5-10
Ok, here's the overview. I'm writing an application which (among other things) can do repetitive writes to the serial port via a timer (the timer runs on a 20 ms period or so, and a write occurs when the timer runs out (over and over). Everthing works fine, except if you try to terminate the application (via the little x) while the continous write is going on. If you do so, you get this error:

VB.NET:
An unhandled exception of type 'System.ObjectDisposedException' occurred in system.windows.forms.dll

Additional information: Cannot access a disposed object named "Form1".

Now, as best as my VB.net-newbie mind can comprehend, this is happening because the thread attacking the serial port is connected to the main frame, and when the frame dissappears, the serial port thread attempts to reference it before .Net can kill it, thus throwing the exception.

Towards this end, I've hooked the "close" signal of the main frame, and done everything possible to stop the serial port... including closing the port, stopping the autowrite timer, purging the in/out buffers, disabling the port's events, setting the serial port object equal to "Nothing", and waiting a long time... but it always gives me the exception, except for one case.

If I hook the "close" signal of the main frame and run a MsgBox... no closing of the serial port, no disabling of the port's events, no nothing, just a msgbox before the window closes (you can even see the main frame updating frantically as the serial port does its thing behind the messagebox)... it works fine - no exceptions.

So that's where I am. Any thoughts/ideas/wild conjectures on how I can avoid the exception without the strange MsgBox workaround?

-Nate
 
Ok, I've solved the problem myself. I was right about the cause of the problem. Adding a msgBox fixed things because it induced a pause (until you click it) while still letting the main form tidy things up in the background. When I added the pause manually, I used the thread.sleep() method, which put the form to sleep. So while it *did* pause, it didn't actually give it time to clean stuff up, so the problem wasn't solved. Now I'm using a timer to induce a 50ms delay between the time you click the "x" and the time the app actually exits, which works perfectly (since it lets the form keep running, thus giving it time to clean up the serial port thread).

Hope that helps someone searching the forum some day :)
 
Maybe you could Abort the Thread in Form Closing event too.
 
Yes JohnH is correct. You need to abort the thread in the forms closing event, then use the .join() method to wait for the thread to end. Then the form will finish closing after the thread is surely finished.
 
Back
Top