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);
}
}