垃圾收集器会调用 Dispose() 吗? [英] Does garbage collector call Dispose()?

查看:20
本文介绍了垃圾收集器会调用 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() 吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆