Dilshod K
Dilshod K

Reputation: 3032

How to kill all threads when WPF app was closed

I have a WPF app. I am starting some threads. When I close the app it is still running in the background (I am seeing from Task Manager) because Threads are still running. I want to kill all threads when the app was closed. Here is the code:

public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
    }

    Thread thread;
    private void Button_Click(object sender, RoutedEventArgs e)
    {
        thread = new Thread(new ParameterizedThreadStart(abc));
        thread.Start();
    }

    private void abc(object obj)
    {
        Thread.Sleep(10000);
    }
}

In this case, when I click the button and close the app, it will still be running in the background for 10 seconds. How can I kill all threads on the closing app?

Upvotes: 1

Views: 1580

Answers (1)

thatguy
thatguy

Reputation: 22089

A thread can either be a foreground or a background thread. From the documentation:

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.

A thread created via the constructor of the Thread class is a foreground thread by default. Consequently, you can make a thread a background thread to terminate it when your application closes by setting the IsBackground property to true:

private void Button_Click(object sender, RoutedEventArgs e)
{
   thread = new Thread(new ParameterizedThreadStart(abc));
   thread.IsBackground = true;
   thread.Start();
}

Upvotes: 5

Related Questions