DEV Community

Cover image for šŸ› ļø Pro Tip: Implementing IDisposable for Proper Resource Management
DotNet Full Stack Dev
DotNet Full Stack Dev

Posted on

šŸ› ļø Pro Tip: Implementing IDisposable for Proper Resource Management

When working with unmanaged resources (e.g., file handles, database connections), implementing IDisposable ensures they are properly released. Here's how you can do it in 3 steps:

Step 1: Implement IDisposable Interface

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

    // Example: Unmanaged resource
    private IntPtr unmanagedResource;

    public ResourceHandler()
    {
        // Initialize resource
        unmanagedResource = // allocate unmanaged resource;
    }

    // Dispose method for cleaning up resources
    public void Dispose()
    {
        Dispose(true);
        GC.SuppressFinalize(this);
    }

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

            // Release unmanaged resources here
            if (unmanagedResource != IntPtr.Zero)
            {
                // Free the unmanaged resource
                unmanagedResource = IntPtr.Zero;
            }

            disposed = true;
        }
    }
}

Enter fullscreen mode Exit fullscreen mode

Step 2: Use using Statement to Automatically Call Dispose()

using (var handler = new ResourceHandler())
{
    // Work with the resource
}

Enter fullscreen mode Exit fullscreen mode

Step 3: Ensure Proper Cleanup with Finalizer (if needed)

~ResourceHandler()
{
    Dispose(false);
}

Enter fullscreen mode Exit fullscreen mode

šŸ“Œ Highlights:
Step 1: Implement IDisposable and handle cleanup logic for both managed and unmanaged resources.
Step 2: Use the using statement for automatic resource cleanup.
Step 3: Add a finalizer if needed to ensure resources are released if Dispose is not called.
This ensures that resources are properly managed, avoiding potential memory leaks and resource exhaustion.

Top comments (0)

šŸ‘‹ Kindness is contagious

Please leave a ā¤ļø or a friendly comment on this post if you found it helpful!

Okay