In a class with managed and unmanaged resources

suggest change

It’s important to let finalization ignore managed resources. The finalizer runs on another thread – it’s possible that the managed objects don’t exist anymore by the time the finalizer runs. Implementing a protected Dispose(bool) method is a common practice to ensure managed resources do not have their Dispose method called from a finalizer.

public class ManagedAndUnmanagedObject : IDisposable
{
    private SqlConnection sqlConnection = new SqlConnection();
    private UnmanagedHandle unmanagedHandle = Win32.SomeUnmanagedResource();
    private bool disposed;

    public void Dispose()
    {
        Dispose(true); // client called dispose
        GC.SuppressFinalize(this); // tell the GC to not execute the Finalizer
    }

    protected virtual void Dispose(bool disposeManaged)
    {
        if (!disposed)
        {
            if (disposeManaged)
            {
                if (sqlConnection != null)
                {
                    sqlConnection.Dispose();
                }
            }

            unmanagedHandle.Release();

            disposed = true;
        }
    }

    ~ManagedAndUnmanagedObject()
    {
        Dispose(false);
    }
}

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:


IDisposable interface:
* In a class with managed and unmanaged resources

Table Of Contents
17 Regex
19 Arrays
21 Enum
22 Tuples
24 GUID
27 Looping
36 Casting
46 Methods
60 IDisposable interface
88 Events
92 Structs
104 Indexer
106 Stream
107 Timers
109 Threading
127 Caching
135 Pointers
147 C# Script