垃圾收集器是否调用 Dispose()?

Does garbage collector call Dispose()?(垃圾收集器是否调用 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()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

DispatcherQueue null when trying to update Ui property in ViewModel(尝试更新ViewModel中的Ui属性时DispatcherQueue为空)
Drawing over all windows on multiple monitors(在多个监视器上绘制所有窗口)
Programmatically show the desktop(以编程方式显示桌面)
c# Generic Setlt;Tgt; implementation to access objects by type(按类型访问对象的C#泛型集实现)
InvalidOperationException When using Context Injection in ASP.Net Core(在ASP.NET核心中使用上下文注入时发生InvalidOperationException)
LINQ many-to-many relationship, how to write a correct WHERE clause?(LINQ多对多关系,如何写一个正确的WHERE子句?)