gpt4 book ai didi

c# - 为什么 HashAlgorithm 类要实现 IDisposable?

转载 作者:行者123 更新时间:2023-12-03 22:02:13 25 4
gpt4 key购买 nike

使用时 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com