gpt4 book ai didi

.net - 什么时候AppDomain.ProcessExit不会被调用?

转载 作者:行者123 更新时间:2023-12-03 02:13:27 25 4
gpt4 key购买 nike

启用下面的行 //1 将使程序崩溃而不打印“proc exit”,但在 //2 行的情况下,将打印“proc exit”。顺便说一句,“unhandled”在两种情况下都会被打印。

为什么会有差异,一般规则是什么?显然使用例如杀死一个应用程序任务管理器会阻止打印“proc exit”,但除此之外,还有哪些情况不打印?

static void Main(string[] args)
{
Thread.GetDomain().UnhandledException +=
(sender, eventArgs) => Console.WriteLine("unhandled");
AppDomain.CurrentDomain.ProcessExit +=
(sender, eventArgs) => Console.WriteLine("proc exit");
//1 new Thread(_ => { throw new Exception(); }).Start();
//2 ThreadPool.QueueUserWorkItem(_ => { throw new Exception(); });
Thread.Sleep(1000);
return;

最佳答案

请看一下这篇博文:AppDomain.ProcessExit is not guaranteed to be called 。引自帖子:

The AppDomain.ProcessExit is not guaranteed to be called. It's pretty resilient and will deal with common things you may cause from low-trust IL (exceptions, out-of-memory, etc), but there are some things (like rude process shutdown), that an inprocess event can never be resilient against.

(...)

The callback is invoked from within the process. If the process rudely exits, the callback would not be invoked. Common sources for rudely exiting include:

  1. Killed externally via TaskManager or kernel32!TerminateProcess.
  2. Stackoverflow handler consumes past the guard page.

The ProcessExit event is like telling somebody "please telephone me that your about to die". If death comes quickly enough, they may not get the message out.

事实上,我已经尝试过你的代码,当取消注释第 1 行甚至第 2 行时,它从不打印“proc exit”! (我尝试在 Visual Studio 2013 中针对所有 .NET 版本进行编译)。当然,当没有抛出异常并且进程正常退出时,它会打印它。 (编辑:如果在 Release模式下编译代码,我会看到“proc exit”消息,但在 Debug模式下编译时不会看到“proc exit”消息)

作为旁注,这里是对您的代码的建议重构(未经过充分测试,可能不完整,但您明白了):

static void Main(string[] args)
{
Thread.GetDomain().UnhandledException +=
(sender, eventArgs) => Exiting((Exception)eventArgs.ExceptionObject);
AppDomain.CurrentDomain.ProcessExit +=
(sender, eventArgs) => Exiting(null);
//1 new Thread(_ => { throw new Exception(); }).Start();
//2 ThreadPool.QueueUserWorkItem(_ => { throw new Exception(); });
Thread.Sleep(1000);
return;
}

static void Exiting(Exception exception)
{
//Put common cleanup code here (or at the end of the method)

if(exception == null)
{
Console.WriteLine("normal proc exit");
}
else
{
Console.WriteLine("unhandled exception: " + exception.GetType().Name);
}
}

关于.net - 什么时候AppDomain.ProcessExit不会被调用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20675024/

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