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


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




C# creating as many instances of a class as there are processors

1:



How to keep track of thread progress in Python without freezing the PyQt GUI?
Mark your thread as BackgroundThread, and it will stop running as soon as you close the window..
multiple lock in same function


Java synchronization not working as (I) expected


Can client side python use threads?

2:



Controlling iPhone App Flow During Table View Animations
I think the debug vs.


WCF Self Hosting Performance
release mode is a red herring.


j2me networking, threads and deadlocks
In release mode, you're just not getting the dialog box with the "cannot access a disposed object" error..


3:


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.


4:


Make sure that the other thread is set as background thread.. Also, in Application.Exit make otherThread.Join().


5:


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..


6:


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



74 out of 100 based on 54 user ratings 854 reviews