gpt4 book ai didi

c# - 后台线程的预期 ThreadAbort

转载 作者:太空狗 更新时间:2023-10-30 00:26:51 27 4
gpt4 key购买 nike

我有以下内容。

public static Thread testThread = new Thread(ThreadStart) {Name = "TestThread", IsBackground = true};
private void Form_Load()
{
testThread.Start()
}
private static void ThreadStart()
{
int count = 0;
try
{
while (true)
{
count++;
}
}
catch (Exception ex)
{

StreamWriter stream = new StreamWriter(File.OpenWrite("Exception.txt"));
stream.WriteLine(count + "\n" + ex);
stream.Flush();
stream.Close();
}
}

当我调用 Thread.Abort() 时,我捕捉到异常并写入文件。但是,如果我关闭应用程序,则不会写入任何内容。我也有

AppDomain.CurrentDomain.UnhandledException +=
new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);
Application.SetUnhandledExceptionMode(UnhandledExceptionMode.ThrowException);
Application.ThreadException +=
new System.Threading.ThreadExceptionEventHandler(Application_ThreadException);

但似乎从未抛出过异常。

我想添加一个问题是明智的。

当父进程退出时,正在运行的后台线程会发生什么?我的理解是抛出 ThreadAbortException 以退出线程。如果是这种情况,如何捕获 ThreadAbortException 以清理线程中可能存在的资源?

最佳答案

首先,应用程序可能没有退出,因为您没有将它们变成后台线程。我的猜测是任务管理器会显示意外运行的 EXE 副本。在调用 Start 之前,您需要在线程对象上将 Thread.IsBackground 设置为 true。

其次,the documentation 明确揭穿了您期望的行为:

Note

When the common language runtime (CLR) stops background threads,after all foreground threads in a managed executable have ended, itdoes not use System.Threading.Thread.Abort. Therefore, you cannot useThreadAbortException to detect when background threads are beingterminated by the CLR.

编辑:

当进程退出时,不需要清理工作线程持有的资源,因为,您知道,进程正在退出。关于后台线程的约定是它们可以在进程退出时随时被杀死。因此,如果您的后台线程正在做一些需要事务正确性的事情,那么它们可能不应该是后台线程。让他们成为前台线程,并让他们定期检查或等待重置事件,看看他们是否应该退出并允许进程结束。

关于c# - 后台线程的预期 ThreadAbort,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9152534/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com