释放资源 的相关注意事项

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Runtime.InteropServices;

namespace ConsoleApp_DisposeResources
{
class Program
{
static void Main(string[] args)
{
SampleClass sample=new SampleClass();
sample.Dispose();
Console.ReadKey();
}
}

public class GlobalRes
{
//对于静态变量,如果数据量比较大,用完后应当赋值为null,减少内存占用
public static List<string> FileNameList = new List<string>();

public void Method1()
{
//using等同于下面的try finally
//using (SampleClass sample = new SampleClass())
//{}

//SampleClass sample2 = new SampleClass();
//try
//{

//}
//finally
//{
// sample2.Dispose();
//}
}
}

/// <summary>
/// 托管资源和非托管资源的清理
/// </summary>
public class SampleClass : IDisposable
{
/*
* 托管资源:
* 由CLR管理分配和释放的资源,即从CLR里new出来的对象()
*
* 非托管资源:
* 不受CLR管理的对象,需要手动释放,如Windows内核对象,stream,文件,数据库连接,COM对象,GDI+的相关对象等
* 以及ApplicationContext,Brush,Component,ComponentDesigner,Container,Context,Cursor,
* FileStream,Font,Icon,Image,Matrix,Object,OdbcDataReader,OleDBDataReader,Pen,Regex,Socket,StreamWriter等
*/

//非托管资源
private IntPtr localResource = Marshal.AllocHGlobal(100);

//托管资源(可以直接调用Dispose释放)
Component managedResource = new Component();

private bool disposed = false;

/// <summary>
/// 实现接口
/// </summary>
public void Dispose()
{
Dispose(true);

//请求系统不要调用指定对象的终结器
GC.SuppressFinalize(this);
}

/// <summary>
/// 析构函数/类型的终结器,防止忘记显示调用Dispose
/// </summary>
~SampleClass()
{
Dispose(false);//必须为false
}

/// <summary>
/// 非密封类修饰用protected virtual
/// 密封类修饰用private
/// </summary>
protected virtual void Dispose(bool disposing)
{
if (disposed) return;

if (disposing)
{
//清理托管资源
if (managedResource != null)
{
managedResource.Dispose();
managedResource = null;
}

//清理非托管资源
if (localResource != IntPtr.Zero)
{
Marshal.FreeHGlobal(localResource);
localResource = IntPtr.Zero;
}
}
disposed = true;
}
}
}

原文地址:https://www.cnblogs.com/jx270/p/3660230.html