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. 程序主動釋放。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM