110,567
社区成员
发帖
与我相关
我的任务
分享
一般在Dispose的时候,要释放非托管资源。比如下面的例子My对象申请了一段非托管内存(以便和本地dll通讯等等),如果没有释放该资源,那么将造成内存泄露。
至于及时释放托管资源,则用IComponent模式更加合适。有兴趣你可看ComponentModel下的IContainer和IComponent。
请注意我的例子为求简单,没有用Dispose(bool disposing)模式,不会自动销毁。
using System;
using System.Runtime.InteropServices;
namespace ConsoleApplication1
{
class Program
{
public static event EventHandler DoSomething;
static void Main(string[] args)
{
My my = new My();
FireDoSomethingEvent(); // ok
my.Dispose();
FireDoSomethingEvent(); // <---- 将出现异常
}
static void FireDoSomethingEvent()
{
if (Program.DoSomething != null)
{
Program.DoSomething(null, EventArgs.Empty);
}
}
}
class My : IDisposable
{
public My()
{
data = Marshal.AllocHGlobal(16 * 1024); // 申请非托管内存
Program.DoSomething += new EventHandler( this.OnDoSomething );
}
public void Dispose()
{
Marshal.FreeHGlobal(data); // 释放非托管内存
data = IntPtr.Zero;
}
private void OnDoSomething(object sender, EventArgs e)
{
Marshal.WriteInt32(data, 1234); // 写入非托管内存
//CallNativeMethod(data); // 调用非托管dll...
}
private IntPtr data;
}
}