什么时候在ASP.NET中为C#类调用析构函数? [英] When is destructor called for C# classes in ASP.NET?
问题描述
说,我有一个这样定义的C#类:
Say, I have my own C# class defined as such:
public class MyClass
{
public MyClass()
{
//Do the work
}
~MyClass()
{
//Destructor
}
}
然后我从ASP.NET项目创建我的类的实例,如下例如:
And then I create an instance of my class from an ASP.NET project, as such:
if(true)
{
MyClass c = new MyClass();
//Do some work with 'c'
//Shouldn't destructor for 'c' be called here?
}
//Continue on
我希望在 if
范围的末尾调用的析构函数,但永远不会调用。我缺少什么?
I'd expect the destructor to be called at the end of the if
scope but it never is called. What am I missing?
推荐答案
与C ++析构函数等效的是 IDisposable
和 Dispose()
方法,通常在 using
块中使用。
The equivalent to a C++ destructor is IDisposable
and the Dispose()
method, often used in a using
block.
请参见 http://msdn.microsoft.com/ zh-cn / library / system.idisposable.aspx
您所说的析构函数通常称为 Finalizer 。
What you are calling a destructor is better known as a Finalizer
.
这是使用IDisposable的方法。请注意,不会自动调用 Dispose()
。最好的办法是使用 using
,这将使 Dispose()
即使 using
块中有一个异常,也不会终止。
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.
}
您可以调用 .Dispose()
如果需要的话,请明确自己。 using
的唯一要点是当执行离开 using时自动调用
出于任何原因阻止。 .Dispose()
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.
有关更多信息,请参见此处: http://msdn.microsoft.com/zh-cn/library/yh598w02%28v=vs.110%29.aspx
See here for more info: http://msdn.microsoft.com/en-us/library/yh598w02%28v=vs.110%29.aspx
基本上,上面的 using
块等效于:
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();
}
这篇关于什么时候在ASP.NET中为C#类调用析构函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!