我們自訂的類並不像表單類那樣當表單關閉時自動調用釋放函數(實際上是重載基類函數)如下:
/// <summary>
/// 清理所有正在使用的資源。
/// </summary>
/// <param name="disposing">如果應釋放託管資源,為 true;否則為 false。</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
因為我們定義類的在表單執行個體化時分配空間但當該表單關閉時並沒有釋放該類,如果一個時時操作的C/S結構的系統.很容易使記憶體用完而死機.所以對類要做介面.如下:
public class LinkDataBase:IDisposable
{
//解構函式
~LinkDataBase()
{
Dispose(true);
}
public void Dispose()
{
Dispose(true);
}
/// <summary>
/// 清理所有正在使用的資源。
/// </summary>
/// <param name="isDisposing">如果應釋放託管資源,為 true;否則為 false</param>
protected virtual void Dispose(bool isDisposing)
{
// Don't dispose more than one
if (_alreadyDisposed)
return;
if (isDisposing)
{
GC.SuppressFinalize(this);
}
// TODO: free unmanaged resources here
// Set disposed flag
_alreadyDisposed = true;
}
這樣當我們關閉執行個體化該的表單時調用一下就行了,如下:
LinkDataBase link = new LinkDataBase();
private void configure_FormClosed(object sender, FormClosedEventArgs e)
{
l ink.Dispose();
}