GC.Collect() 没有立即收集?

GC.Collect() not collecting immediately?(GC.Collect() 没有立即收集?)
本文介绍了GC.Collect() 没有立即收集?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在聊天讨论过程中,我编写了这个控制台应用程序.

In the course of a discussion in chat, I wrote this console application.

using System;

class Program
{
    static void Main(string[] args)
    {
        CreateClass();
        Console.Write("Collecting... ");
        GC.Collect();
        Console.WriteLine("Done");
    }

    static void CreateClass()
    {
        SomeClass c = new SomeClass();
    }
}

class SomeClass
{
    ~SomeClass()
    {
        throw new Exception();
    }
}

结果:

Collecting... Done

Unhandled Exception: System.Exception: Exception of type 'System.Exception' was
thrown.
   at SomeClass.Finalize()

我原以为应用会在 Done 打印出来之前崩溃.

I would have expected the app to crash before Done was printed.

我不太关心如何制作它.我的问题是,为什么不呢?

I don't care much about how to make it. My question is, why doesn't it?

推荐答案

不能在单个垃圾收集过程中收集具有终结器的对象.这些对象被移动到 f-reachable 队列,并一直保留在那里直到调用终结器.只有在那之后,它们才能被垃圾收集.

Objects with finalizers cannot be collected within a single garbage collection procedure. Such objects are moved to f-reachable queue, and remain there until finalizers are called. Only after that they can be garbage-collected.

以下代码更好,但无论如何你都不应该依赖它:

Following code is better, but you should not rely on it anyway:

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

另外,在终结器中抛出异常对我来说似乎太残忍了,即使是为了测试目的.

Also, throwing exceptions in finalizer seems too brutal for me, even for testing purposes.

另外,终结器的有趣副作用:如果在终结器中存储 this 引用(将其分配给某个静态变量).

Also, interesting side-effect of finalizers: an object with finalizer can still 'resurrect' itself (effectively prevent garbage collection of itself), if stores this reference in finalizer (assigns it to some static variable).

这篇关于GC.Collect() 没有立即收集?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

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

相关文档推荐

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子句?)