c# - 这个 GCNotification 片段是如何工作的?CLR 通过 C#
问题描述
我现在正在通过 C# 阅读 CLR。在第 21 章托管堆和垃圾收集中,它展示了一个可以在 gc 发生时引发事件的类。我对类的功能只有一些模糊的概念,但我无法理解该类的工作原理以及如何使用它以及它如何与 GenObject 类交互?我已经完成了事件章节。
public static class GCNotification
{
private static Action<Int32> s_gcDone = null;
public static event Action<Int32> GCDone
{
add
{
if (s_gcDone == null)
{
new GenObject(0);
new GenObject(2);
}
s_gcDone += value;
}
remove { s_gcDone -= value; }
}
private sealed class GenObject
{
private readonly Int32 m_generation;
public GenObject(Int32 generation)
{
m_generation = generation;
}
//Finalize 方法
~GenObject()
{
if (GC.GetGeneration(this) >= m_generation)
{
Action<Int32> temp = Volatile.Read(ref s_gcDone);
if (temp != null)
{
temp(m_generation);
}
}
if ((s_gcDone != null) &&
!AppDomain.CurrentDomain.IsFinalizingForUnload() &&
!Environment.HasShutdownStarted)
{
if (m_generation == 0)
{
new GenObject(0);
}
else
{
GC.ReRegisterForFinalize(this);
}
}
else
{
//放过对象
}
}
}
}
解决方案
推荐阅读
- c# - 无法获得 while 循环来检查我的用户输入是否等于某些数字
- python - HTTPS 防止 Python3 中的网站抓取
- javascript - v-on 指令可以直接修改父级的 data() 属性吗?
- c - C 编程 malloc 和 NULL
- javascript - Angular 6 分页与从 Api 获取的数据的 ng-bootstrap
- reactjs - React propTypes 用于“系统提供”的道具
- javascript - 猜数字游戏中的全局变量
- bash - 如何将文件列表移动到目录列表中?
- php - 如何将 SQL 转换为函数
- c# - 我的所有方法都需要一个通用包装器,而无需复制代码(C#)