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.");
}
}
}
三种方式
- 置 NULL (注意:隐式释放)
- 回调 AppDomain.CurrentDomain.ProcessExit
- 程序主动释放。