Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Static Finalizer

What is the right way to perform some static finallization?

There is no static destructor. The AppDomain.DomainUnload event is not raised in the default domain. The AppDomain.ProcessExit event shares the total time of the three seconds (default settings) between all event handlers, so it's not really usable.

like image 475
Michael Damatov Avatar asked Nov 01 '08 20:11

Michael Damatov


People also ask

What is a finalizer in C#?

Finalizers (historically referred to as destructors) are used to perform any necessary final clean-up when a class instance is being collected by the garbage collector. In most cases, you can avoid writing a finalizer by using the System.

What is static destructor?

Static destructors are executed one by one in reverse order to the order of corresponding classes definition. Static destructors are always executed after software entry point and always after constructors of all global objects.

Can static class be dispose C#?

Static items don't support dispose.

Can we dispose static class?

Answers. Static finalizers and destructors are not possible, because types are only unloaded when the AppDomain shuts down.


2 Answers

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

like image 103
Michael Damatov Avatar answered Oct 02 '22 07:10

Michael Damatov


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?

like image 34
Jon Skeet Avatar answered Oct 02 '22 08:10

Jon Skeet