Search code examples
c#.nethashidisposable

Why does the HashAlgorithm class implement IDisposable?


While using MD5CryptoServiceProvider I found that it might need to be disposed since it inherits from HashAlgorithm class which implements IDisposable. However, the example in the docs didn't dispose it.

My question is why HashAlgorithm class implements IDisposable ? Isn't hashing just some computations that take place in memory ? What kind of unmanaged resources might be used in hashing ?


Solution

  • You can have a look at sources

    [System.Security.SecuritySafeCritical] // overrides public transparent member
    protected override void Dispose(bool disposing)
    {
        if (_safeHashHandle != null && !_safeHashHandle.IsClosed)
            _safeHashHandle.Dispose();
        base.Dispose(disposing);
    }
    

    It's disposing the internal SafeHashHandle instance, which is used to wrap the unmanaged resource (operation system handle) and calls Dispose from base HashAlgorithm class. You have to properly dispose and release this handle after usage

    [System.Security.SecurityCritical]
    protected override bool ReleaseHandle()
    {
        FreeHash(handle);
        return true;
    }
    

    This method is override of abstract ReleaseHandle() method from base SafeHandle class. You can read more about this class at MSDN, basically this class is a wrapper to any operation system resource

    It contains a critical finalizer that ensures that the handle is closed and is guaranteed to run during unexpected AppDomain unloads, even in cases when the platform invoke call is assumed to be in a corrupted state.