Does garbage collector call Dispose()?(垃圾收集器是否调用 Dispose()?)
问题描述
我认为如果您的程序没有调用 Dispose,GC 最终会调用 Dispose,但您应该在程序中调用 Dispose() 只是为了使清理具有确定性.
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.
但是,从我的小测试程序中,我根本没有看到 Dispose 被调用....
However, from my little test program, I don't see Dispose getting called at all....
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?
是的,我知道我应该调用 Dispose() - 我在使用一次性物品时确实遵循标准模式.出现我的问题是因为我试图追踪其他人代码中的泄漏,该代码是托管 C++(另一层复杂性,这将是另一个线程的好主题).
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).
推荐答案
GC 不调用 Dispose
,它调用你的终结器(你应该调用 Dispose(false)代码>).
The GC does not call Dispose
, it calls your finalizer (which you should make call Dispose(false)
).
请查看侧面的相关帖子或查找 Dispose 模式的 C# 最佳实践(IDisposable
上的文档很好地解释了 IIRC.)
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()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:垃圾收集器是否调用 Dispose()?
基础教程推荐
- 将 XML 转换为通用列表 2022-01-01
- rabbitmq 的 REST API 2022-01-01
- 如何在 IDE 中获取 Xamarin Studio C# 输出? 2022-01-01
- c# Math.Sqrt 实现 2022-01-01
- 为什么Flurl.Http DownloadFileAsync/Http客户端GetAsync需要 2022-09-30
- SSE 浮点算术是否可重现? 2022-01-01
- 将 Office 安装到 Windows 容器 (servercore:ltsc2019) 失败,错误代码为 17002 2022-01-01
- MS Visual Studio .NET 的替代品 2022-01-01
- 有没有办法忽略 2GB 文件上传的 maxRequestLength 限制? 2022-01-01
- 如何激活MC67中的红灯 2022-01-01