加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 垃圾收集器是否受益于对Collect和WaitForPendingFinalizer

发布时间:2020-12-15 23:33:37 所属栏目:百科 来源:网络整理
导读:我发现这个在线代码是在取消初始化Excel Interop对象后附加的: GC.Collect();GC.WaitForPendingFinalizers();GC.Collect();GC.WaitForPendingFinalizers(); 这是对DRY的准违反(以口吃的方式连续两次调用GC.Collect()和GC.WaitForPendingFinalizers())有什么
我发现这个在线代码是在取消初始化Excel Interop对象后附加的:

GC.Collect();
GC.WaitForPendingFinalizers();
GC.Collect();
GC.WaitForPendingFinalizers();

这是对DRY的准违反(以口吃的方式连续两次调用GC.Collect()和GC.WaitForPendingFinalizers())有什么用处,或者只是浪费时间?

解决方法

这来自Microsoft documentation站点上的示例程序.

//Force garbage collection.
   GC.Collect();

   // Wait for all finalizers to complete before continuing.
   // Without this call to GC.WaitForPendingFinalizers,// the worker loop below might execute at the same time 
   // as the finalizers.
   // With this call,the worker loop executes only after
   // all finalizers have been called.
   GC.WaitForPendingFinalizers();

When the garbage collector finds objects that can be reclaimed,it checks each object to determine the object’s finalization requirements. If an object implements a finalizer and has not disabled finalization by calling SuppressFinalize,the object is placed in a list of objects that are marked as ready for finalization. The garbage collector calls the Finalize methods for the objects in this list and removes the entries from the list. This method blocks until all finalizers have run to completion.

The thread on which finalizers are run is unspecified,so there is no guarantee that this method will terminate. However,this thread can be interrupted by another thread while the WaitForPendingFinalizers method is in progress. For example,you can start another thread that waits for a period of time and then interrupts this thread if this thread is still suspended.

据我所知,没有明确的迹象表明两次调用它的好处.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读