IDisposable的使用

C# 中使用 IDisposable

c#中,如果類使用了非託管資源,該類一般應該實現IDisposable接口來確保資源的正常釋放。

一個類如果使用了非託管資源(例如使用了由C/C++DLL返回的對象,或者昂貴的資源需要儘快釋放,一般需要實現IDisposable接口以便於類的使用者可以顯示的釋放資源。

案例說明:

Public class ResourceHolder : IDisposable

{

       ///<summary>

       ///Implemantation of the IDisposable interface

       ///</summary>

       Public void Dispose()

       {

              // Call internal Dispose(bool)

              Dispose(true);

              // Prevent the destructor from being called

              GC.SuppressFinalize(this);

       }

}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章