首页 > 解决方案 > 这个 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#

解决方案


推荐阅读