使用时 MD5CryptoServiceProvider
我发现它可能需要处理,因为它继承自 HashAlgorithm
实现 IDisposable
的类.然而,the example in the docs没有处置它。
我的问题是为什么HashAlgorithm
类实现 IDisposable
?散列不只是在内存中进行的一些计算吗?什么样的非托管资源可以用于散列?
最佳答案
你可以看看sources
[System.Security.SecuritySafeCritical] // overrides public transparent member
protected override void Dispose(bool disposing)
{
if (_safeHashHandle != null && !_safeHashHandle.IsClosed)
_safeHashHandle.Dispose();
base.Dispose(disposing);
}
它正在处理内部
SafeHashHandle
实例,用于包装非托管资源(操作系统句柄)并调用Dispose
从基地 HashAlgorithm
类(class)。您必须在使用后正确处置和释放此句柄[System.Security.SecurityCritical]
protected override bool ReleaseHandle()
{
FreeHash(handle);
return true;
}
此方法覆盖抽象
ReleaseHandle()
来自基础的方法 SafeHandle
类(class)。您可以在 MSDN 阅读有关该类(class)的更多信息,基本上这个类是任何操作系统资源的包装器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.
关于c# - 为什么 HashAlgorithm 类要实现 IDisposable?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59083838/