跳至內容

C Sharp/Object Lifetime

維基教科書,自由的教學讀本

程序的資源釋放有三種方法:

  • 受管資源由垃圾回收器自動釋放
  • 非受管資源,必須實現IDisposable接口,用Dispose方法顯式釋放
  • 調用System.GC.Collect()方法直接立即回收垃圾

對於實現了IDisposable的對象,一旦使用完就應該立即顯式調用Dispose方法釋放資源。using是它的語法糖。

終結器中應該調用Dispose()作為最後的補救措施。

以下為dispose pattern的用例:

public class MyResource : IDisposable
{
    private IntPtr _someUnmanagedResource;
    private List<long> _someManagedResource = new List<long>();
    
    public MyResource()
    {
        _someUnmanagedResource = AllocateSomeMemory();
        
        for (long i = 0; i < 10000000; i++)
            _someManagedResource.Add(i);
        ...
    }
    
    // The finalizer will call the internal dispose method, telling it not to free managed resources.
    ~MyResource()
    {
        this.Dispose(false);
    }
    
    // The internal dispose method.
    private void Dispose(bool disposing)
    {
        if (disposing)
        {
            // Clean up managed resources
            _someManagedResource.Clear();
        }
        
        // Clean up unmanaged resources
        FreeSomeMemory(_someUnmanagedResource);
    }
    
    // The public dispose method will call the internal dispose method, telling it to free managed resources.
    public void Dispose()
    {
        this.Dispose(true);
        // Tell the garbage collector to not call the finalizer because we have already freed resources.
        GC.SuppressFinalize(this);
    }
}