I wasn't able to get a definitive answer on this so this question. There are few SO posts in the past that mentioned that instances of HashAlgorithm
are not thread-safe quoting snippet in the MSDN doc.
See
- Why does SHA1.ComputeHash fail under high load with many threads?
- HMACSHA1.ComputeHash() thread-safety question
- Which piece of code is more performant?
But, the current MSDN doc doesn't say so. Surprisingly, the below code doesn't bomb on net3.1, net5.0, but does on net6.0. So, it looks like it was made thread-safe (perhaps), but perhaps net6.0 has a bug.
//<TargetFrameworks>net6.0;net5.0;netcoreapp3.1;net48</TargetFrameworks>
[Explicit]
[Test]
public void Bork_HashAlgorithm()
{
const int iterations = 1_000_000;
var bytes = Encoding.UTF8.GetBytes("the overtinkerer");
using (var md5 = MD5.Create())
{
Parallel.For(0, iterations, (i, loop) =>
{
md5.ComputeHash(bytes);
});
}
}
Exception message:
SafeHandle cannot be null. (Parameter 'pHandle')