c# – 垃圾收集保证

前端之家收集整理的这篇文章主要介绍了c# – 垃圾收集保证前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
垃圾收集器有什么保证?

根据我的研究,我找到了:

>如果仍然存在对内存的引用,则不会对其进行垃圾回收
>如果没有参考:

>当它是GC时是非确定性的
>当GC释放到终结器时,将在释放内存之前运行.
>无法保证终结者的顺序(所以不要假设父母将在孩子之前运行).

但我真正想知道的是:

是否保证所有内存最终都将被垃圾收集并且终结器(析构函数)在对象上运行(假设程序退出很好).例如,最终退出时没有内存压力的应用程序会强制GC查找所有对象并确保调用终结器(析构函数)(包括静态成员变量)?

我确实在这个页面上找到了一个引用:
http://www.c-sharpcorner.com/UploadFile/tkagarwal/MemoryManagementInNet11232005064832AM/MemoryManagementInNet.aspx

In addition,by default,Finalize methods are not called for unreachable objects when an application exits so that the application may terminate quickly.

但我不确定这句话是多么权威.

我还找到了以下文档:
CriticalFinalizerObject

解决方法

Is there a guarantee that all memory
will eventually be garbage collected
and the finalizer (destructor) run on
the object (assuming the program
exited nicely).

不可以.从Object.Finalize文档中可以清楚地看出,如果使用终结器,则不会调用终结器

>其他一些终结器无法正常完成:

Another finalizer blocks indefinitely
(goes into an infinite loop,tries to
obtain a lock it can never obtain and
so on). Because the runtime attempts
to run finalizers to completion,other
finalizers might not be called if a
finalizer blocks indefinitely.

>其他一些终结者创造更多
制作它的最终目标
不可能完成所有
可终结的对象:

The runtime continues to Finalize
objects during shutdown only while the
number of finalizable objects
continues to decrease.

>其他一些终结者抛出异常:

If Finalize or an override of Finalize
throws an exception,and the runtime
is not hosted by an application that
overrides the default policy,the
runtime terminates the process and no
active try-finally blocks or
finalizers are executed. This behavior
ensures process integrity if the
finalizer cannot free or destroy
resources.

话虽这么说,除非有必要,否则你有更多理由不想使用终结器.

>他们放慢了垃圾收集器的速度(甚至可以减慢它这么多,记忆不是回收尽快用完).>他们在另一个线程上运行,带来多线程问题发挥作用.>他们没有被执行确定性秩序.>他们可以复活那些对象已经敲定(而且不会除非明确说明,否则重新注册以完成最终确定).

猜你在找的C#相关文章