开发者

static destructor

开发者 https://www.devze.com 2023-01-29 14:29 出处:网络
C# has static constructor which do some initialization (likely do some unmanaged resource initialization).开发者_如何学Python

C# has static constructor which do some initialization (likely do some unmanaged resource initialization).开发者_如何学Python

I am wondering if there is static destructor?


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


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.


Initializing and cleaning up unmanaged resources from a Static implementation is quite problematic and prone to issues.

Why not use a singleton, and implement a Finalizer for the instance (an ideally inherit from SafeHandle)


No there is nothing like destructor for static classes but you can use Appdomain.Unloaded event if you really need to do something

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号