Herfried Wagner has written an excellent article explaining how to implement this – alas, in German (and VB). Still, the code should be understandable.

I've tried it:

static readonly Finalizer finalizer = new Finalizer();

sealed class Finalizer {
  ~Finalizer() {
    Thread.Sleep(1000);
    Console.WriteLine("one");
    Thread.Sleep(1000);
    Console.WriteLine("two");
    Thread.Sleep(1000);
    Console.WriteLine("three");
    Thread.Sleep(1000);
    Console.WriteLine("four");
    Thread.Sleep(1000);
    Console.WriteLine("five");
  }
}

It seems to work exactly the same way as the AppDomain.ProcessExit event does: the finalizer gets ca. three seconds...


Basically, you can't. Design your way around it to the fullest extent possible.

Don't forget that a program can always terminate abruptly anyway - someone pulling out the power being the obvious example. So anything you do has to be "best effort" - in which case I'd certainly hope that AppDomain.ProcessExit would be good enough.

What do you need to do, in your particular case?