Click here to Skip to main content
15,881,882 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
I use threads in my .net Windows application. When I close my application then the threads should be stopped, but they still keep on running. Does anybody know the answer how we kill threads when the application gets closed.

Thanks in advance!
Posted
Updated 30-Mar-11 1:10am
v2
Comments
CPallini 30-Mar-11 6:44am    
As correctly answered below, threads don't survive after the process terminates.
Sergey Alexandrovich Kryukov 30-Mar-11 15:02pm    
But the problem is: a running thread will prevent process termination, if it is not the thread from the thread pool.
--SA

Have a look at this thread on Stack Overflow

http://stackoverflow.com/questions/3542061/how-do-i-stop-a-thread-when-my-winform-application-closes[^]

In particular, the second answer should give you a clue

" If you create the new threads as background threads (by setting IsBackground before starting them), they will automatically stop when the main thread (the application thread) terminates."

(From MSDN):

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.
 
Share this answer
 
v2
Comments
Manfred Rudolf Bihy 30-Mar-11 7:08am    
Good answer! 5+
Proposed as solution.
Sergey Alexandrovich Kryukov 30-Mar-11 15:02pm    
All correct, my 5.
--SA
Sergey Alexandrovich Kryukov 30-Mar-11 15:13pm    
Will you also see my Answer and comments? I think this is very interesting.
--SA
Espen Harlinn 30-Mar-11 15:59pm    
My 5 - good reply!
Either do what Dylan already proposed (I recommend that) or you can also keep track of which Threads you started in your application and then use Thread.Abort() to kill them.

Best Regards,
 
Share this answer
 
Comments
Sergey Alexandrovich Kryukov 30-Mar-11 15:12pm    
This is correct and important addition, my 5. However, I decided whole my Answer to discuss Abort and the responsibility it may entail. Please see my Answer and especially my discussion with Olivier I reference -- I think it is very interesting.
Thank you.
--SA
Espen Harlinn 30-Mar-11 15:59pm    
Good advice - my 5!
This is the additional note for additional note, by Manfred. :-)

Of course you can use Thread.Abort and you should do it in some situations, but you need to do it very responsibly. In all cases you should handle ThreadAbortException exception. Strictly speaking, if this is the very end of the application run-time, you might ignore it and any related problems. I don't recommend it; it could badly hurt supportability of your code.

Think about just one thing, for example: what happens if you thread opened some files with write access and some data need flush? Handling ThreadAbortException allows you to handle all "post-mortal" situations.

For more detail, please see my discussion with Olivier over his answer to this Question: How do I abort a specific thread that is already running?[^]. Please find a sub-string "exception seeding" to get into the topic. There I tried to provide very little known information on how it works.

—SA
 
Share this answer
 
Comments
Espen Harlinn 30-Mar-11 16:00pm    
Nice additional additions, I've added my 5 :)
Sergey Alexandrovich Kryukov 30-Mar-11 16:03pm    
Thank you, Espen, for the addition.
--SA
Manfred Rudolf Bihy 31-Mar-11 4:22am    
My 5 added!
Sergey Alexandrovich Kryukov 31-Mar-11 13:02pm    
Thank you, Manfred.
--SA
Thanks to everyone for early response . I done all suggested changes but no luck.

I make my thread as background thread but result is the same. Thread is still running.
I also try to kill the thread on Windows Application FormClosed() event but still no luck.

I want to share one thing that my thread is started from "User Control" so when we stop main application the "User Control" thread should also stop or not. Please suggest.
 
Share this answer
 
Hi,

Maybe this approach will work for you:

When writing a Windows Forms application, I tend to use the Application.ApplicationExit event as the trigger to terminate any running threads that the application needed.

How you actually terminate the thread is up to you and the design, but I generally build a kill-switch into the thread-methods's loop. Once that is set to false, the thread method terminates on it's next pass through the loop.

PS: if you have a Monitor.Wait() or AutoResetEvent.WaitOne() holding your thread suspended while it waits for work, don't forget to signal the thread when you want it to stop.

eg:

C#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Windows.Forms;


    class ThreadTerminateExample
    {
        /// <summary>
        /// worker thread.
        /// </summary>
        private Thread _thread;

        /// <summary>
        /// control flag.
        /// </summary>
        private bool _runFlag = true;

        /// <summary>
        /// constructor.
        /// </summary>
        public ThreadTerminateExample()
        {
            _thread = new Thread((ThreadStart)ThreadMethod);
            _thread.Start();

            // handle the application exit event to stop threads on exit.
            Application.ApplicationExit += new EventHandler(Application_ApplicationExit);
        }

        /// <summary>
        /// application exit event handler
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        void Application_ApplicationExit(object sender, EventArgs e)
        {
            // stop the thread.
            StopThread();
        }

        /// <summary>
        /// thread worker method.
        /// </summary>
        private void ThreadMethod()
        {
            while (_runFlag)
            {
                Console.WriteLine("Doing Some Work");
                Thread.Sleep(1000);
            }
        }

        /// <summary>
        /// stop thread method.
        /// </summary>
        private void StopThread()
        {
            _runFlag = false;
            _thread.Join(2000);
            _thread = null;
        }

    }
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900