Loading

C# 静态实例的释放

看图

代码

using System;

namespace Cmd
{
    class Program
    {
        public static void Main(params string[] args)
        {
            Loader.Read();
            Loader.Native = null;
            GC.Collect();
        }
    }

    public static class Loader
    {
        public static void Read() => Native.Read();
        public static Native Native = new Native();
    }

    public class Native : IDisposable
    {
        static Native()
        {
            AppDomain.CurrentDomain.ProcessExit += (m, n) => { Console.WriteLine("exit."); };
        }

        ~Native()
        {
            Console.WriteLine("release native.");
        }
        public void Read()
        {
            Console.WriteLine("read native.");
        }

        public void Dispose()
        {
            Console.WriteLine("dispose native.");
        }
    }
}

三种方式

  1. 置 NULL (注意:隐式释放)
  2. 回调 AppDomain.CurrentDomain.ProcessExit
  3. 程序主动释放。
posted @ 2022-04-11 17:31  microestc  阅读(776)  评论(0编辑  收藏  举报