Dil*_*d K 1 c# wpf multithreading
我有一个 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);
}
}
Run Code Online (Sandbox Code Playgroud)
在这种情况下,当我单击按钮并关闭应用程序时,它仍会在后台运行 10 秒。如何杀死正在关闭的应用程序上的所有线程?
A thread can either be a foreground or a background thread. From the documentation:
后台线程与前台线程相同,只是后台线程不会阻止进程终止。一旦属于某个进程的所有前台线程都终止,公共语言运行时就会结束该进程。任何剩余的后台线程都会停止并且不会完成。
默认情况下,通过类的构造函数创建的线程Thread是前台线程。IsBackground因此,您可以通过将属性设置为:使线程成为后台线程,以便在应用程序关闭时终止它true:
private void Button_Click(object sender, RoutedEventArgs e)
{
thread = new Thread(new ParameterizedThreadStart(abc));
thread.IsBackground = true;
thread.Start();
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1217 次 |
| 最近记录: |