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