什么时候AppDomain.ProcessExit不会被调用? [英] When will AppDomain.ProcessExit not get called?

查看:484
本文介绍了什么时候AppDomain.ProcessExit不会被调用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

启用线路 // 1 以下将使程序崩溃,没有proc退出打印,
,但如果行 // 2 ,将打印proc exit。 未处理的btw将在两种情况下打印。

Enabling line //1 below will make the program crash without "proc exit" being printed, but in case of line //2, "proc exit" will be printed. "unhandled" btw gets printed in both cases.

为什么有区别,一般规则是什么?显然使用例如杀死一个应用程序任务管理员将阻止proc exit的打印,但除此之外,它是什么情况不能打印?

Why the difference, and what are the rules in general? Obviously killing an app using e.g. the task manager will prevent "proc exit" from being printed, but other than that, what are the cases it doesn't get printed?

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;


推荐答案

两种情况没有区别,难以解释为什么你会看到一个。

There is no difference between the two cases, hard to explain why you'd see one.

使用编写的代码,应该不会引发AppDomain.ProcessExit事件。正常的事情应该发生,CLR将异常传递到操作系统,弹出Windows错误报告崩溃对话框。如果异常是程序崩溃的一个已知原因(它不会),那么在用户关闭对话框时,该程序会终止程序。所以没有ProcessExit事件。

With the code as written, the AppDomain.ProcessExit event should never be raised. The normal thing should happen, the CLR passes the exception to the operating system and the Windows Error Reporting crash dialog pops up. It trundles for a while to check with Microsoft servers if the exception is a known reason for programs to crash (it won't be), then terminates the program when the user dismisses the dialog. So no ProcessExit event.

你可以编写你的代码,以便提高ProcessExit 。它需要你不要把它放在操作系统上来照顾它。你必须自己关闭程序。您通过使用AppDomain.UnhandledException事件处理程序自己明确终止程序来执行此操作。像这样:

You can certainly write your code so that ProcessExit will be raised. It requires you not leaving it up to the operating system to take care of it. You must shut down the program yourself. Which you do by explicitly terminating the program yourself with your AppDomain.UnhandledException event handler. Like this:

    Thread.GetDomain().UnhandledException += (s, e) => {
        var ex = (Exception)e.ExceptionObject;
        Console.WriteLine(ex.ToString());
        Environment.Exit(System.Runtime.InteropServices.Marshal.GetHRForException(ex));
    };

您可以选择如何终止程序。我显示了Environment.Exit(),但您也可以考虑使用Environment.FailFast()来即时中止请求,而不再运行任何代码。这更安全,但当然你也不会得到ProcessExit。

You do have a choice on how you terminate the program. I showed Environment.Exit() but you could also consider Environment.FailFast() to ask for an instant abort without running any more code. That's safer but of course you won't get ProcessExit either.

这篇关于什么时候AppDomain.ProcessExit不会被调用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆