- c - 在位数组中找到第一个零
- linux - Unix 显示有关匹配两种模式之一的文件的信息
- 正则表达式替换多个文件
- linux - 隐藏来自 xtrace 的命令
我有以下内容。
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/
我有以下内容。 public static Thread testThread = new Thread(ThreadStart) {Name = "TestThread", IsBackground
我是一名优秀的程序员,十分优秀!