static destructor
This is the best way (ref: https://stackoverflow.com/a/256278/372666)
public static class Foo
{
private static readonly Destructor Finalise = new Destructor();
static Foo()
{
// One time only constructor.
}
private sealed class Destructor
{
~Destructor()
{
// One time only destructor.
}
}
}
No, there isn't.
A static destructor supposedly would run at the end of execution of a process. When a process dies, all memory/handles associated with it will get released by the operating system.
If your program should do a specific action at the end of execution (like a transactional database engine, flushing its cache), it's going to be far more difficult to correctly handle than just a piece of code that runs at the end of normal execution of the process. You have to manually handle crashes and unexpected termination of the process and try recovering at next run anyway. The "static destructor" concept wouldn't help that much.
No, there isn't. The closest thing you can do is set an event handler
to the DomainUnload
event on the AppDomain
and perform your cleanup there.
Not exactly a destructor, but here is how you would do it:
class StaticClass
{
static StaticClass() {
AppDomain.CurrentDomain.ProcessExit +=
StaticClass_Dtor;
}
static void StaticClass_Dtor(object sender, EventArgs e) {
// clean it up
}
}