Static finalizer

What is the correct way to do some static finalization?

There is no static destructor. The AppDomain.DomainUnload event is not displayed in the default domain. The AppDomain.ProcessExit event shares the total time of three seconds (default settings) between all event handlers, so it cannot be used.

+36
c # static destructor finalizer
Nov 01 '08 at 20:35
source share
5 answers

Basically, you cannot. Build your path around it as much as possible.

Do not forget that a program can always abruptly stop - someone pulls out a force, which is an obvious example. So, everything you do should be the "best effort", in which case, of course, I hope that AppDomain.ProcessExit will be good enough.

What do you need to do in your particular case?

+27
Nov 01 '08 at 20:40
source share

Herfried Wagner wrote an excellent article explaining how to implement this - alas, in German (and VB). However, the code should be clear.

I tried:

 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 just like the AppDomain.ProcessExit event does: the finalizer gets ok. three seconds...

+38
Nov 01 '08 at 23:51
source share

I would question what you load in your static methods that should be released. Of course, I would not recommend doing this in a static method.

However, your static method can create an object that has a finalize method.

+6
Nov 01 '08 at 20:40
source share

Two solutions that come to mind:

  • Do not use a static class. If you use a non-static class and create one, you don’t have to worry about cleaning up.
  • If this is not an option, I would say that it is a good situation to use a singleton. This will instantiate a copy of your object and call the finalizer on exit, but still allow you to consider it as a static class for the most part. After all, your class is already static and therefore shares most of the common reasons for not using singleton.
+6
Nov 01 '08 at 20:59
source share

Send Michael Damatov an answer (C #), which is based on Herfried C. Wagner. (VB.NET) here 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!"); } 

PS Like AppDomain.ProcessExit, this call cannot be called if the process aborts abnormally (for example, from the task manager). Another caveat is that if MyClass is shared (templated), the assumption that its static constructor and static destructor will be called no more than once per application execution is no longer valid.

0
Jul 31 '14 at 20:03
source share



All Articles