Anonymous Cow
Anonymous Cow

Reputation:

Why do I get an error after closing my Windows Forms application?

When I run my Visual Studio Windows Forms application by clicking F5 (debug mode), after I click on the close button (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).

Upvotes: 2

Views: 823

Answers (6)

George Mauer
George Mauer

Reputation: 122052

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

Upvotes: 1

GEOCHET
GEOCHET

Reputation: 21323

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);

Upvotes: 0

Chris Marasti-Georg
Chris Marasti-Georg

Reputation: 34650

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.

Upvotes: 0

Nenad Dobrilovic
Nenad Dobrilovic

Reputation: 1555

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

Upvotes: 4

John K
John K

Reputation: 2180

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.

Upvotes: 3

Sunny Milenov
Sunny Milenov

Reputation: 22310

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

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

Upvotes: 0

Related Questions