Question

My application on startup may start a few thread concurrently. Now based on some condition I would like to completely kill off all the thread regardless the state of other threads.

I have tried App.Current.ShutDown() as well as Application.Current.ShutDown but doesn't work?

Was it helpful?

Solution

You can try

Environment.Exit(0);

You can replace 0 with any code you want from here

You should see Killing all threads that opened by application (and Shutting down a multithreaded application consequently) as I think he provides some solid advice.

OTHER TIPS

A thread is either a background thread or a foreground thread. Background threads are identical to foreground threads, except that background threads do not prevent a process from terminating. Once all foreground threads belonging to a process have terminated, the common language runtime ends the process. Any remaining background threads are stopped and do not complete.

Set your thread's property IsBackground=true

var t= new Thread();
t.IsBackground = true;

Also See this: How to: Create and Terminate Threads (C# Programming Guide)

If you need to kill the running application, regardless of state you can either use

Environment.Exit(0); // use -1 if you're exiting with an error, exiting with 0 is considered to have exited without errors.

Or if you really want to use the hammer

Environment.FailFast()

FailFast's documentation says: Immediately terminates a process after writing a message to the Windows Application event log, and then includes the message in error reporting to Microsoft.

Use the FailFast method instead of the Exit method to terminate your application if the state of your application is damaged beyond repair, and executing your application's try/finally blocks and finalizers will corrupt program resources.

If your other threads are background threads they will end (i.e. abort silently when you shutdown the WPF application which is running on the only foreground thread):

From MSDN:

"...background threads do not prevent a process from terminating. Once all foreground threads belonging to a process have terminated, the common language runtime ends the process. Any remaining background threads are stopped and do not complete."

e.g.

Thread myThread = new Thread();
myThread.IsBackground = true;

ThreadPool threads background ones.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top