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.
To port Michael Damatov's answer (C#) which is based on Herfried K. Wagner. (VB.NET) here is the C++/CLI version:
P.S. Just like the AppDomain.ProcessExit method, this one may not be called if the process is terminated abnormally (from Task Manager for example). Another word of caution is that if MyClass is generic (templated), the assumption that its static constructor and static destructor will be called no more than once per application execution is no longer be valid.
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?
Two solutions that jump to mind:
I would question what you are loading in your static methods that need to be released. I certainly wouldn't recommend doing these things in a static method.
That said, your static method could instanciate an object that has a finalise method.
I've tried it:
It seems to work exactly the same way as the
AppDomain.ProcessExit
event does: the finalizer gets ca. three seconds...