据我了解,如果我设置_myThread.isBackground = true
,那么线程应该在表单关闭时退出。不幸的是,我没有发现我的线程正在退出。我的代码如下所示:
private void MainForm_Load(object sender, EventArgs e)
{
// <snip>
daemon = new Daemon();
// <snip>
}
public Daemon()
{
// Start the main thread which will do most of the connection checking and work
_mainThread = new Thread(() => MainThread(this));
_mainThread.IsBackground = true;
_mainThread.Start();
}
/// <summary>
/// This is the work that the main thread does.
/// </summary>
private void MainThread(Daemon daemon)
{
while(true)
{
try
{
// Do things.
Thread.Sleep(2000); // Sleep for a bit to not hammer.
}
catch (Exception e)
{
Logger.Exception(e);
}
}
}
我认为,由于线程是从表单启动的,因此设置 isBackground=true 会强制它在表单退出时关闭。
我是否遗漏或误解了某些内容?
最佳答案
严格来说,该线程是后台线程阻止它保持进程处于事件状态。只要至少有一个非后台线程在运行,该进程就会一直存在。 UI 线程是非后台线程,默认情况下,winform 应用程序中关闭主线程将导致该线程完成。
现在我们已经掌握了所有这些,我们可以看到,关闭主窗体通常会“杀死”后台进程,但是有很多事情可以阻止这种情况。
主线程结束并不一定意味着应用程序将结束,并且 UI 线程将终止。人们可以调整应用程序的行为以在不同的条件下结束,或者添加代码以在应用程序完成运行后在 Main
中运行。
您还可以创建其他非 UI 线程,如果这样做,它们将使整个进程(以及所有后台线程)保持事件状态。
关于c# - 为什么窗体关闭时后台线程不退出?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30946618/