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

标签 c# .net hash idisposable

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

相关文章:

python - Pandas :TypeError:无法散列的类型: 'list'

C# 列表数字排序

带接口(interface)的 C# 泛型

C# 使用 LINQ 读取和过滤 CSV 文件

.net - 如何使我的托管 NuGet 包支持 C++/CLI 项目?

ruby-on-rails - 在 rails 中插入要散列的属性

c# - Xamarin (XAML) 如何并排放置 2 个标签

c# - 在 XAML 中添加数学公式的好方法?

c# - 是否有针对对象的轻型和重型版本的设计模式?

ruby - 如何比较两个哈希值?