简体   繁体   中英

Why not static destructors in C#

I am interested in knowing why static destructors are not allowed in C#. Note that I am not supposing that they exist in any other language.

I could have a class like this one.

 class A
 {
      static A()
      {
         // here I can load a resource that will be avaliable for all instances 
         // of this class.
      }
 }

When the application ends I may need to release the resource.

So, the semantic of a static destructor could be the following: called when the application ends, for classes that contain it and were initialized in the app.

Your semantic is one possible one, but I guess you have not checked all effects it would have on the language. In most (more or less) dynamic languages I know, destruction is a much more complicated topic that it looks like. Why not call the destructor when the class is not referenced anymore? Or if the assembly is unloaded? In what order should destructor be called? ...?

If you just want to execute some code when the application ends, have a look at the .Net documentation. There are easier and more reliable ways to do so.

So, the semantic of a static destructor could be the following: - be called when the application ends, on class that contains it and was charged in the app.

Your semantic relies on your program doing an specific action at the end of execution and this is far more difficult to correctly handle than just a piece of code that runs at the end of normal execution of the process.

Think about transactions or file management operations. You have to manually handle crashes and unexpected termination of the process and try recovering at next run anyway, so then having an static destructor wouldn't help that much. .NET managed world favors upon using patterns instead of that. Now, if you're having serious problems with this, try to attach an event handler to the DomainUnloaded event on the AppDomain and perform your cleanup there.

You can, also, give a try to the singleton dispose way:

class A : IDisposable
{
    public static A Instance {get; private set;}

    public static A()
    {
        Instance=new A();
    }

    public void MethodA() {...}

    public void Dispose()
    {
        //...
    }

    ~A()
    {
        // Release your hard resources here
    }
}

And then, use the safe method:

A.Instance.MethodA();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM