我有一个WPF应用程序。我正在启动一些线程。当我关闭应用程序时,它仍在后台运行(从任务管理器中看到),因为线程仍在运行。我想在应用程序关闭时杀死所有线程。这是代码:
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);
}
}
在这种情况下,当我单击按钮并关闭应用程序时,它仍将在后台运行10秒钟。如何杀死正在关闭的应用程序上的所有线程?
答案 0 :(得分:3)
线程可以是前台线程或后台线程。来自documentation:
除后台线程不会阻止进程终止外,后台线程与前台线程相同。一旦属于某个进程的所有前台线程都已终止,公共语言运行库将终止该进程。 所有剩余的后台线程都已停止并且未完成。
通过Thread
类的构造函数创建的线程默认情况下是前台线程。因此,可以通过将IsBackground
属性设置为true
,将线程设为后台线程以在应用程序关闭时终止该线程:
private void Button_Click(object sender, RoutedEventArgs e)
{
thread = new Thread(new ParameterizedThreadStart(abc));
thread.IsBackground = true;
thread.Start();
}