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

来源:互联网 发布:flash编程入门教程 编辑:程序博客网 时间:2024/05/16 13:40

背景

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

方案

方案一

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

  1. /// <summary>
  2. /// Clean up any resources being used.
  3. /// </summary>
  4. /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
  5. protected override void Dispose(bool disposing)
  6. {
  7.     if (disposing && (components != null))
  8.     {
  9.         components.Dispose();
  10.     }
  11.     base.Dispose(disposing);
  12. }
复制代码

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

  1. /// <summary>
  2. /// Clean up any resources being used.
  3. /// </summary>
  4. /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
  5. protected override void Dispose(bool disposing)
  6. {
  7.     if (disposing && (components != null))
  8.     {
  9.         components.Dispose();
  10.     }
  11.     DisposeResources();
  12.     base.Dispose(disposing);
  13. }
复制代码

方案二

注册Disposed事件。

  1. this.Disposed += new EventHandler(MainForm_Disposed);
  2. void MainForm_Disposed(object sender, EventArgs e)
  3. {
  4.     Logger.Instance.LogTrace("MainForm_Disposed");
  5. }
复制代码

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

  1. if (disposing && (components != null))
  2. {
  3.     components.Dispose();
  4. }
复制代码

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

方案三

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

  1. internal class Disposer : Component
  2. {
  3.     private IDisposable _disposable;
  4.     internal Disposer(IDisposable disposable)
  5.     {
  6.         _disposable = disposable;
  7.     }
  8.     protected override void Dispose(bool disposing)
  9.     {
  10.         if (disposing)
  11.         {
  12.             if (_disposable != null)
  13.             {
  14.                 _disposable.Dispose();
  15.             }
  16.         }
  17.         base.Dispose(disposing);
  18.     }
  19. }
复制代码

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

  1. components.Add(new Disposer(connectionManager));
复制代码

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

  1. if (disposing && (components != null))
  2. {
  3.     components.Dispose();
  4. }
复制代码

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

  1. sealed class ConnectionManager : IDisposable
  2. {
  3.     public void Dispose()
  4.     {
  5.         //Disconnect the network
  6.     }
  7. }
复制代码

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