实例上对Dispose方法的调用会调用垃圾收集器吗? [英] Does call to the Dispose method on a instance invoke Garbage Collector?

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

问题描述

如果我们显式调用Dispose mehtod,它将调用垃圾回收器(GC)吗?


当我们使用using块时,是否在块的末尾调用了(GC)?

If we call Dispose mehtod explicitly, will it invoke Garbage collector(GC)?

or
when we use using block, Is it(GC) called at the end of the block?

using(StreamWriter sw=File.CreateText(@"D:\fs.txt"))
          {
              sw.Write("writing using stream writer\r\n");
          }

推荐答案

不,不是. using语句使用System.IDisposeable:
https://msdn.microsoft.com/en-us/library/Aa664736%28v = VS.71%29.aspx [ ^ ],
https://msdn.microsoft.com/en-us/library/yh598w02.aspx [ ^ ],
https://msdn.microsoft.com/en-us/library/system.idisposable.aspx [ ^ ].

与GC相比,此接口用作以受控方式执行任何清理操作的方式.它通常用于释放任何非托管资源,但可以用于任何事物.特别是,I/O对象使用它来刷新缓冲区并关闭句柄.还有许多其他用户.

对于GC,将根据可达性和通过引用的对象等标准回收所有托管内存.这个标准比人们想象的要复杂得多.请参阅: http://en.wikipedia.org/wiki/Garbage_collection_(computer_science) [ ^ ].

另请参阅Wes Aday对问题的评论.该应用程序无法控制何时进行垃圾回收.您没有引用就放弃了该对象.同时,例如,如果3个对象在循环中互相引用,并且没有更多的引用,则无论如何它们将被回收.它会在一段时间后发生,您无法控制.当发生这种情况时,将调用对象的析构函数.这就是析构函数很少被编写的原因.仅当其他调用析构函数且时序绝对不重要时,才可以使用此技术.

—SA
No, it does not. The using statement uses System.IDisposeable:
https://msdn.microsoft.com/en-us/library/Aa664736%28v=VS.71%29.aspx[^],
https://msdn.microsoft.com/en-us/library/yh598w02.aspx[^],
https://msdn.microsoft.com/en-us/library/system.idisposable.aspx[^].

This interface is used as the way to perform any clean-up action in controlled manner, in contrast to GC. It is often used to release any unmanaged resource, but can be used for anything. In particular, I/O objects use it to flush the buffer and close handles. There are many other users.

As to GC, all managed memory is reclaimed based on such criterion as reachability and objects via references. This criterion is much more complicated that one could think. Please see: http://en.wikipedia.org/wiki/Garbage_collection_(computer_science)[^].

See also the comment to the question by Wes Aday. The application cannot control when garbage collection takes place. You abandon the object by having no references to it. At the same time, if, for example, 3 objects reference each other in cycle and there are no more references, they will be reclaimed anyway. It happens some time later, which you cannot control. And when it happens, object''s destructor is called. This is the reason why destructors are written quite rarely; this technique can be used only if other of calling destructors and timing is absolutely non-critical.

—SA


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

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