Saturday, 9 August 2025

Dispose Pattern (Advanced) for both managed and unmanaged resources

🔄 Dispose Pattern (Advanced) If your class holds both managed and unmanaged resources, implement the full dispose pattern:

public class MyResource : IDisposable
{
    private bool disposed = false;

    public void Dispose()
    {
        Dispose(true);
        GC.SuppressFinalize(this);  // Prevent finalizer from running
    }

    protected virtual void Dispose(bool disposing)
    {
        if (!disposed)
        {
            if (disposing)
            {
                // Dispose managed resources
            }

            // Release unmanaged resources
            disposed = true;
        }
    }

    ~MyResource()
    {
        Dispose(false);  // Finalizer only releases unmanaged resources
    }
}

📋 Best Practices ✅ Always use using for short-lived disposable objects. ✅ Implement IDisposable if your class owns disposable fields. ✅ Call GC.SuppressFinalize(this) in Dispose() if you have a finalizer. ✅ Make Dispose() idempotent — safe to call multiple times.
Share:

0 Comments:

Post a Comment