Windows Mobile使用.NET Compact Framework開發Winform時如何Dispose資源

來源:互聯網
上載者:User
背景

在開發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。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.