析构函数 - 它被调用,如果应用程序崩溃应用程序、函数

2023-09-04 00:53:03 作者:刚好遇见你

做了析构函数被调用,如果应用程序崩溃?如果它是一个未处理的异常,我猜是这样,但对于更严重的错误,或者像一个用户查杀应用程序?

Does a destructor get called if the app crashes? If it's an unhandled exception I'm guessing it does, but what about more serious errors, or something like a user killing the application process?

和几个潜在的愚蠢的问题:

And a few more potentially dumb questions:

会发生什么在一个应用程序的应用程序退出,所有的终结已经执行时的所有对象 - 做对象被垃圾收集的还是他们在某种程度上所有的卸载的进程或应用程序域? 是每个应用的垃圾收集器部分(在同一进程中运行)或者是独立?

推荐答案

我会鼓励你去尝试自己这一点。例如:

I would encourage you to try this for yourself. For example:

using System;

class Program {
  static void Main(string[] args) {
    var t = new Test();
    throw new Exception("kaboom");
  }
}
class Test {
  ~Test() { Console.WriteLine("finalizer called"); }
}

运行此命令提示符,所以你可以看到奄奄一息。先用throw语句注释掉。

Run this at the command prompt so you can see the last gasp. First with the throw statement commented out.

就像在Windows中的任何未处理的异常,默认异常过滤器,Windows提供了调用Windows错误报告对话框中,通过WerFault.exe显示。如果您单击关闭程序,WerFault将使用TerminateProcess()杀程序。这是一个快结束时,有没有机会跑了终结器线程,当一个程序正常退出会发生。

Like any unhandled exception in Windows, the default exception filter that Windows provides invokes the Windows Error Reporting dialog, displayed by WerFault.exe. If you click "Close program", WerFault will use TerminateProcess() to kill the program. That's a quick end, there is no opportunity to run the finalizer thread, as would happen when a program exits normally.

Windows下,那么负责清理起来的弹片。它会自动关闭任何操作系统处理程序可能已经打开,但没有得到一个机会,将在今年终结。文件是这里的棘手问题,它们的缓冲区没有得到刷新,你会很容易地结束了磁盘上的部分写入文件。

Windows then takes care of cleanup up the shrapnel. It automatically closes any operating system handles your program might have opened but didn't get a chance to close in the finalizer. Files are the trickier problem here, their buffers don't get flushed and you'll easily end up with a partially written file on disk.