[ACCEPTED]-Static Finalizer-finalizer

Accepted answer
Score: 49

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

I've 3 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 2 way as the AppDomain.ProcessExit event does: the finalizer gets 1 ca. three seconds...

Score: 33

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

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

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

Score: 8

Two solutions that jump to mind:

  • Don't use a static class. If you use a non-static class and instantiate it, you don't have to worry about cleanup as much.
  • If that's not an option, I'd argue that this is a good situation to use a singleton. This will instantiate a copy of your object and have the finalizer called on exit, but still allow you to treat it like a static class for the most part. After all, your class is static already and therefore shares most of the common reasons not to use a singleton.

0

Score: 6

I would question what you are loading in 5 your static methods that need to be released. I 4 certainly wouldn't recommend doing these 3 things in a static method.

That said, your 2 static method could instanciate an object 1 that has a finalise method.

Score: 1

To port Michael Damatov's answer (C#) which 10 is based on Herfried K. Wagner. (VB.NET) here 9 is the C++/CLI version:

ref class MyClass
{
        ref class StaticFinalizer sealed
        {
            !StaticFinalizer();
        };
        static initonly StaticFinalizer^ stDestr = gcnew StaticFinalizer();
}

MyClass::StaticFinalizer::!StaticFinalizer()
{
    System::Diagnostics::Debug::WriteLine("In StaticFinalizer!");
}

P.S. Just like the 8 AppDomain.ProcessExit method, this one may 7 not be called if the process is terminated 6 abnormally (from Task Manager for example). Another 5 word of caution is that if MyClass is generic 4 (templated), the assumption that its static 3 constructor and static destructor will be 2 called no more than once per application 1 execution is no longer be valid.

More Related questions