When is destructor called for C# classes in ASP.NET?

▼魔方 西西 提交于 2019-12-05 04:39:18

The equivalent to a C++ destructor is IDisposable and the Dispose() method, often used in a using block.

See http://msdn.microsoft.com/en-us/library/system.idisposable.aspx

What you are calling a destructor is better known as a Finalizer.

Here's how you would use IDisposable. Note that Dispose() is not automatically called; the best you can do is to use using which will cause Dispose() to be called, even if there is an exception within the using block before it reaches the end.

public class MyClass: IDisposable
{
    public MyClass()
    {
        //Do the work
    }

    public void Dispose()
    {
        // Clean stuff up.
    }
}

Then you could use it like this:

using (MyClass c = new MyClass())
{
    // Do some work with 'C'
    // Even if there is an exception, c.Dispose() will be called before
    // the 'using' block is exited.
}

You can call .Dispose() explicitly yourself if you need to. The only point of using is to automate calling .Dispose() when execution leaves the using block for any reason.

See here for more info: http://msdn.microsoft.com/en-us/library/yh598w02%28v=vs.110%29.aspx

Basically, the using block above is equivalent to:

MyClass c = new MyClass();

try
{
    // Do some work with 'C'
}

finally
{
    if (c != null)
        ((IDisposable)c).Dispose();
}
Tigran

There is no way you can control a timing or make a guess on when actually destructor of the object will be called. It's all up to the Garbage Collector.

The only think you can be sure, in this case, that at the moment you leave that scope the object c becomes unreachable (I assume there are no global references to that instance inside the scope), so the instance c is intended to be identified and removed by Garbage Collector when time comes.

It is up to the garbage collector as to when an object is freed up. However you can force an object to be freed up by calling Finalize. or GC.Collect which will force the garbage collector to take action.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!