在finalize方法中调用配置 [英] Calling dispose in finalize method

查看:71
本文介绍了在finalize方法中调用配置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是面试问题之一...我们可以在finalize 方法中调用dispose 方法,因为finalize() 是由垃圾收集器自动调用的,所以我们在finalize中可以全部使用dispose 吗?
dispose finalize之间有什么区别?

This is one of the interview questions... can we call dispose method inside finalize method because finalize() is called automatically by the Garbage Collector, so can we all dispose in finalize.
What''s the difference between dispose and finalize?

推荐答案

您应该考虑告诉您此面试问题的答案不会提高您的整体经历达到可以为您找到工作的水平.

Dispose 是您可以自称的东西.如果您无法调用Finalise ,它会为您调用.因此,使用dispose 方法可以使我们控制清理资源.
You should consider that telling you the answer to this interview question will not raise your overall experience to the level that will get you a job.

Dispose is something you can call yourself. Finalise calls it for you if you failed to call it. Thus, the dispose method is used to give us control over cleaning up of resources.


1. Dispose IDisposable 界面的一部分,并通过调用方法Dispose 或"using"语句进行显式调用,该语句自动进行调用.

2.在MSDN上有一篇有关它的文章:
http://msdn.microsoft.com/en-us/library/b1yfkh5e.aspx [ ^ ].
1. Dispose is part of IDisposable interface and is called explicitly by invoking method Dispose or by "using" statement, which calls it automatically.

2. There is an article about it on MSDN:
http://msdn.microsoft.com/en-us/library/b1yfkh5e.aspx[^].


是的,我们可以在Finalize()中调用dispose 方法.

这样,我们强制dispose 方法被自动调用.

我们可以在Finalize()Dispose 方法中调用dispose方法,使用GC.SuppressFinalize抑制finalize 方法.

下面是该模式的示例代码.这是我们清理未分配资源的最佳方法,是的,不要忘记,我们不会遭受两次运行垃圾回收器的打击.它将抑制finalize 方法,从而避免两次跳闸.

Yes, we can call dispose method in Finalize().

By doing this, we force the dispose method to be called automatically.

We can call the dispose method in Finalize() and in Dispose method, suppress the finalize method using GC.SuppressFinalize.

Below is the sample code of the pattern. This is the best way we do clean our unallocated resources and yes not to forget we do not get the hit of running the Garbage collector twice. It will suppress the finalize method thus avoiding the two trips.

Public Class ClsTesting
  Implements IDisposable
    Public Overloads Sub Dispose()Implements IDisposable.Dispose
      ' write ytour clean up code here
        GC.SuppressFinalize(Me)
    End Sub
    Protected Overrides Sub Finalize()
       Dispose()
    End Sub
 End Class



希望这可以对您有所帮助. :)



Hope this may help you. :)


这篇关于在finalize方法中调用配置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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