Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Destructor - does it get called if the app crashes

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:

  • what happens to all the objects in an app when the app exits and all finalizers have been executed - do the objects get garbage collected or are they somehow all "unloaded" with the process or appdomain?
  • is the garbage collector part of each application (runs in the same process) or is it independent?
like image 536
anakic Avatar asked Mar 25 '10 10:03

anakic


People also ask

What happens when an application crashes?

An app that is written using native-code languages crashes if there's an unhandled signal, such as SIGSEGV, during its execution. When an app crashes, Android terminates the app's process and displays a dialog to let the user know that the app has stopped, as shown in figure 1.


1 Answers

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"); }
}

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

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 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.

like image 98
Hans Passant Avatar answered Oct 15 '22 16:10

Hans Passant