Windows Mobile使用.NET Compact Framework开发Winform时如何Dispose资源

背景

在开发3G应用的时候,程序退出了,需要自动关闭已经打开的链接。这样需要在Winform退出的时候把其分配的资源都dispose掉。本文讲述Winform Dispose资源的几种方法。

 

方案

方案一

使用VS2005以上做Winform开发,Visual Studio会自动生成一个用于保存layout信息和处理事件的partial class(一般叫做*.Designer.cs)这个partial class里面重载了Dispose的方法。

/// <summary>
///
Clean up any resources being used.
/// </summary>
/// <param name="disposing">
true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}

但是这个partial class是由Visual Studio自动生成的,最好不要手工修改,需要Dispose最简单的方法是把这个方法拷贝到另外一个类文件里面。一般为*.cs,然后加入需要Dispose的代码。

/// <summary>
///
Clean up any resources being used.
/// </summary>
/// <param name="disposing">
true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
DisposeResources();
base.Dispose(disposing);
}

 

方案二

注册Disposed事件。

this.Disposed += new EventHandler(MainForm_Disposed);

 

void MainForm_Disposed(object sender, EventArgs e)
{
Logger.Instance.LogTrace("MainForm_Disposed");
}

 

当Dispose调用下面代码的时候会调用该注册的事件处理函数。

if (disposing && (components != null))
{
components.Dispose();
}

 

可是这个方法有一个问题,如果该Form没有任何其他的components 时,MainForm_Disposed是不会被调用的,因此有下面方案三。

 

方案三

由于方案二的问题,提出了方案三。方案三是使用一个继承于Component的类Disposer,这个Disposer类保存需要Dispose的类的引用,然后把这个Disposer类加入到components中。

internal class Disposer : Component
{
private IDisposable _disposable;
internal Disposer(IDisposable disposable)
{
_disposable = disposable;
}

protected override void Dispose(bool disposing)
{
if (disposing)
{
if (_disposable != null)
{
_disposable.Dispose();
}
}
base.Dispose(disposing);
}
}

定义一个继承于Component的类Disposer。Disposer保存了需要Dispose的类的引用。

components.Add(new Disposer(connectionManager));

Disposer的对象保存到 components里面,这样components 就不可能为null。下面的代码就会执行。

if (disposing && (components != null))
{
components.Dispose();
}

connectionManager为需要Dispose的成员,这个对象的类需要继承IDisposable 并重载Dispose。

sealed class ConnectionManager : IDisposable
{
public void Dispose()
{
//Disconnect the network
}
}

 

方案三就完成了,大家merry chrismas。

posted @ 2009-12-24 13:37  Jake Lin  阅读(2671)  评论(12编辑  收藏  举报