C# 垃圾收集器会调用 Dispose() 吗?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1691846/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Does garbage collector call Dispose()?
提问by noctonura
I thought the GC would call Dispose eventually if your program did not but that you should call Dispose() in your program just to make the cleanup deterministic.
我认为 GC 最终会调用 Dispose,如果您的程序没有,但您应该在程序中调用 Dispose() 只是为了使清理具有确定性。
However, from my little test program, I don't see Dispose getting called at all....
但是,从我的小测试程序中,我根本没有看到 Dispose 被调用......
public class Test : IDisposable
{
static void Main(string[] args)
{
Test s = new Test();
s = null;
GC.Collect();
Console.ReadLine();
}
public Test()
{
Console.WriteLine("Constructor");
}
public void Dispose()
{
Console.WriteLine("Dispose");
}
}
// Output is just "Constructor", I don't get "Dispose" as I would expect. What's up?
// 输出只是“构造函数”,我没有像我期望的那样得到“处置”。这是怎么回事?
EDIT:Yes, I know I should call Dispose() - I do follow the standard pattern when using disposable objects. My question arises because I'm trying to track down a leak in somebody elses code, which is managed C++ (another layer of complexity that would be the good subject of another thread).
编辑:是的,我知道我应该调用 Dispose() - 在使用一次性对象时我确实遵循标准模式。我的问题出现是因为我试图追踪其他人代码中的泄漏,该代码由 C++ 托管(另一层复杂性将成为另一个线程的好主题)。
采纳答案by Eloff
The GC does not call Dispose
, it calls your finalizer (which you should make call Dispose(false)
).
GC 不会调用Dispose
,它会调用您的终结器(您应该调用它Dispose(false)
)。
Please look at the related posts on the side or look up the C# best practices for the Dispose pattern (The docs on IDisposable
explain it quite well IIRC.)
请查看旁边的相关帖子或查找 Dispose 模式的 C# 最佳实践(有关IDisposable
IIRC的文档对其进行了很好的解释。)
回答by Dave Black
Short answer is "no". More detailed answers can be found on my replies to "Is it bad practice to depend on the .NET Garbage Collector"and "What happens if I don't call Dispose()"
简短的回答是“不”。可以在我对“依赖 .NET 垃圾收集器是不是不好的做法”和“如果我不调用 Dispose() 会发生什么”的回复中找到更详细的答案