Closing threads on Application Exit?
Hello, I am writing an application that uses multiple threads (background workers).
When the user clicks the "Exit" button in my application the program exits, calling Application.Exit();. On the Application.OnExit event I have a few methods that are called to restore the user's system settings back to the way it was before my application was required to modify them.
Right now I am not using any specific code to handle the closing of threads. When you exit the application the application simply exits. Is there something that I should be doing before I exit my application? Is there some method I should be calling to deal with the threads that are most likely in the middle of processing something?
Also the threads are terminated by default when the Application.Exit() call is invoked, right?
Re: Closing threads on Application Exit?
You could use the WorkerSupportsCancellation property of the BackgroundWorker Class and cancel your BackgroundWorkers before exiting the application. When WorkerSupportsCancellation is true, you can use the CancelAsync method to cancel a specific BGWorker.
And Yes, once the main thread is killed, the threads its started a supposed to be killed too.
Hope this helps.
Re: Closing threads on Application Exit?
Quote:
Originally Posted by
stlaural
And Yes, once the main thread is killed, the threads its started a supposed to be killed too.
That's not quite true. A thread can be either a foreground thread or a background thread. The one and only difference is that background threads are terminated when the application exits and foreground threads aren't. If you're using BackgroundWorkers then you're using background threads. If you want your worker threads to be terminated automatically then that's fine. If you want to be able to cleanup first, you should explicitly create your own Thread objects and don't set their IsBackground property to True. That way, you can set a flag or the like from the UI thread and then call Application.Exit, but each worker thread will have the chance to perform its own cleanup before terminating.
Re: Closing threads on Application Exit?
Quote:
Originally Posted by
jmcilhinney
That's not quite true.
Yep that's right. Thanks Jmc.
I should make it a habit to give more details, I guess as he mentionned he's using BackgroundWorkers, I didn't.