将垃圾收集器调用IDisposable.Dispose我吗? [英] Will the Garbage Collector call IDisposable.Dispose for me?

查看:151
本文介绍了将垃圾收集器调用IDisposable.Dispose我吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在.NET IDisposable模式意味着的,如果你写一个终结,并实现IDisposable,你的终结需要显式调用Dispose。 这是合乎逻辑的,而这也正是我在终结是必要的少数情况下,一直在做。

The .NET IDisposable Pattern implies that if you write a finalizer, and implement IDisposable, that your finalizer needs to explicitly call Dispose. This is logical, and is what I've always done in the rare situations where a finalizer is warranted.

不过,如果我只是这样做会发生什么:

However, what happens if I just do this:

class Foo : IDisposable
{
     public void Dispose(){ CloseSomeHandle(); }
}

和没有实现一个终结,或任何东西。请问框架调用Dispose方法给我吗?

and don't implement a finalizer, or anything. Will the framework call the Dispose method for me?

是的,我知道这听起​​来很愚蠢,而且所有的逻辑意味着它不会,但我一直有两件事情在我的后脑勺已让我无法确定。

Yes I realise this sounds dumb, and all logic implies that it won't, but I've always had 2 things at the back of my head which have made me unsure.

  1. 有人在几年前曾经告诉我,这将在事实上做到这一点,那人出了一个非常坚实的业绩知道自己的东西。

  1. Someone a few years ago once told me that it would in fact do this, and that person had a very solid track record of "knowing their stuff."

编译器/架构做其他神奇的事情取决于哪些接口你实现(例如:的foreach,扩展方法,系列化基于属性等),因此它是有道理的,这可能是魔力太。

The compiler/framework does other 'magic' things depending on what interfaces you implement (eg: foreach, extension methods, serialization based on attributes, etc), so it makes sense that this might be 'magic' too.

虽然我读了很多东西吧,而且有过很多事情暗示的,我从来没有能够找到一个明确是或否的回答这个问题。

While I've read a lot of stuff about it, and there's been lots of things implied, I've never been able to find a definitive Yes or No answer to this question.

推荐答案

在.NET垃圾收集器调用垃圾回收对象的Object.Finalize方法。通过默认这样做的什么并必须overidden如果要释放更多的资源。

The .Net Garbage Collector calls the Object.Finalize method of an object on garbage collection. By default this does nothing and must be overidden if you want to free additional resources.

处置不自动调用,并且必须是明确地称为如果资源被释放,诸如在使用或尝试终于'块

Dispose is NOT automatically called and must be explicity called if resources are to be released, such as within a 'using' or 'try finally' block

看<一href="http://msdn.microsoft.com/en-us/library/system.object.finalize.aspx">http://msdn.microsoft.com/en-us/library/system.object.finalize.aspx有关更多信息,

这篇关于将垃圾收集器调用IDisposable.Dispose我吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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