static destructor

后端 未结 6 1666
情歌与酒
情歌与酒 2020-12-04 17:46

C# has static constructor which do some initialization (likely do some unmanaged resource initialization).

I am wondering if there is static destructor?

相关标签:
6条回答
  • 2020-12-04 17:52

    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.

    0 讨论(0)
  • 2020-12-04 17:54

    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
       }
    }
    
    0 讨论(0)
  • 2020-12-04 17:57

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

    0 讨论(0)
  • 2020-12-04 17:58

    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)

    0 讨论(0)
  • 2020-12-04 18:01

    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.

    0 讨论(0)
  • 2020-12-04 18:06

    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.
            }
        }
    }
    
    0 讨论(0)
提交回复
热议问题