C# reminder: When working with MD5 and SHA hash classes in a loop, remember to call Dispose()
Posted: (EET/GMT+2)
Does your .NET application need to calculate cryptographic hash values of input data? If yes, and you are using classes like MD5, SHA1 or SHA256 for the work, remember that these classes do have the Dispose() method which you should call.
More specifically, most hash algorithms you use are derived from the System.Security.Cryptography.HashAlgorithm class, which implements the IDisposable interface. If you are using the, say, MD5 class to calculate just one or two hash values, calling the Dispose() method isn't paramount, as the garbage collector can do work for you. This is suggested in my C# FAQ post on MSDN from 2006.
However, if you are calling the hash functions in a loop, or otherwise dozens or hundreds of times in a short period time, do remember to call the Dispose() method in due time.
Let's say this post serves an update to the almost ten year old original FAQ post.
Hope this helps, and happy hacking!