How to shutdown threads when an app closes?

UncleRonin

Well-known member
Joined
Feb 28, 2006
Messages
230
Location
South Africa
Programming Experience
5-10
Righto. I have an app which has a thread running continuously throughout the app's lifetime. When the main form closes the app closes. What is the best way to shutdown this thread?

At the moment, when I start the thread I add it to a collection (ArrayList). When I close the app I cycle through the collection and call .Abort() for all active threads. In the thread i encapsulate all the code in a try catch and catch the exeption thrown when the thread is aborted. There is no special code executed within the thread it just gets the status of various databases and servers.

Is this the right way to go about shutting down my thread or is there a better way (I'm guessing there is >_<) ?

Another question, if in the thread I connect to a db and before it closes the connection the exception is thrown (the Con.Close() is in a nested try catch's finally block). The nested finally should still execute before going to the thread's exception handling block?
 
Don't worry about them, when your app closes all associated threads are killed. Your app i assume will be running in a STA (Single Threaded Apartment) therefore any thread that is started is a child, for the want of a better word, of the main UI thread.

Yes, thats what 'finally' is for, it always executes.
 
Are you sure the threads close? I've tested the app without aborting the threads and VS stays in Running mode even after the main app has closed. I initialize the thread the forms load event.
 
Hang on, you just got me thinking. Background threads will abort if the application is exited, however foreground threads may keep the app 'alive' these threads will have to be aborted.
progress.gif
 
Back
Top