C# 關於類資源的釋放

來源:互聯網
上載者:User
我們自訂的類並不像表單類那樣當表單關閉時自動調用釋放函數(實際上是重載基類函數)如下:
       /// <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();

        }

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.