有没有垃圾回收器调用Dispose()?垃圾、Dispose

2023-09-02 10:26:44 作者:爷不死,汝等终究是孙子

我认为,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() - 我做的遵循标准模式使用一次性对象时。我的问题是,因为我试图追查在偷别人的code,这是托管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(假))。

The GC does not call Dispose, it calls your finalizer (which you should make call Dispose(false)).

请看看侧面的相关帖子或查找C#的最佳实践的Dispose模式(本的在的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.)