views:

461

answers:

6

When I run my vs.net winforms application by clicking F5 (debug mode), after I click on the close (which calls Application.Exit();), after a few seconds I get an error that says:

cannot acess a disposed object: Object name 'SampleForm'.

A bit of background, I have another thread that runs every x seconds.

My guess is that when I close the application, and since it is still in debug mode, the other thread is still running and it tries to access something but since I close the application the form is disposed.

Is this correct?

Do I have to kill the background process thread in before I call Application.Exit()?

Update

Now when I call thread.Abort() before the call to Application.Exit(); the application closes completely, before EVEN after I clicked on the close button the debugger was still running (i.e. the stop button was not selected) so it must have been because the thread was still active).

+1  A: 

Yes, you need to kill the thread first.

This really has nothing to do with debug mode though. This has to do with basic threading.

EDIT: Per your update, you should not be aborting the thread. The thread should be getting signaled and exiting on it's own. I am not sure what your thread or code looks like, but something like:

do {

    // Crazy threading stuff here

}while(_running);
Geoffrey Chetwood
A: 

Make sure that the other thread is set as background thread.

Also, in Application.Exit make otherThread.Join()

Sunny
+3  A: 

I think the debug vs. release mode is a red herring. In release mode, you're just not getting the dialog box with the "cannot access a disposed object" error.

John K
+4  A: 

Mark your thread as BackgroundThread, and it will stop running as soon as you close the window.

Nenad
A: 

Yes, you definitely need to kill the threads you spawn. In this case, you check to see if the UI object you are accessing is disposed, and if so, abort the current thread. Another possibility would simple be to keep track of your threads and kill them on exit. A third possibility would be to look into the system ThreadPool and BackgroundWorker areas, to see if they handle any sort of thread lifecycle management like that.

Chris Marasti-Georg
+1  A: 

Set the thread to run in background mode Thread.IsBackground = true. The default is foreground mode which causes it to keep the process alive (even though the UI has closed).

Scroll down to Foreground and Background Threads here for more info

George Mauer