【发布时间】:2015-06-20 04:30:19
【问题描述】:
据我了解,如果我设置了_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 会强制它在表单退出时关闭。
我是否遗漏或误解了什么?
【问题讨论】:
-
后台线程不会在您关闭表单时停止,它们会在所有前台线程终止时停止。所以在我看来,有些东西不会终止(或阻止终止)您的前台线程。关闭窗体时使用 Visual Studio 中的调试器查看所有线程的状态...
-
您编写的代码在我的机器上干净地退出(没有挂起的后台进程)。我怀疑您有另一个非后台线程阻止 clr 关闭应用程序。
-
这段代码如何证明它没有结束后台线程?另外,应用程序关闭后它会运行多长时间?
-
如果给定的答案之一是该问题的已接受答案,那么您应该通过单击答案旁边的空心复选标记来接受它,使其变为绿色。如果您找到了不同的解决方案,那么您应该在此处描述并接受它。
标签: c# multithreading