.NET:处理 HashAlgorithm 对象
从 HashAlgorithm 派生的对象(例如 MD5CryptoServiceProvider)具有 Dispose() 方法,但它是私有的。 相反,它有一个 Clear() 方法,可以“释放它使用的所有资源”。
搞什么?
这是正确处理 HashAlgorithm 的方法吗?
var hasher = new MD5CryptoServiceProvider();
byte[] hashCode = hasher.ComputeHash(data);
hasher.Clear();
有人想向我解释一下这个吗? :)
Objects that derive from HashAlgorithm such as MD5CryptoServiceProvider have a Dispose() method, but it's private. Instead it has a Clear() method which "Releases all resources" used by it.
WTF?
Is this how to correctly dispose of a HashAlgorithm then?
var hasher = new MD5CryptoServiceProvider();
byte[] hashCode = hasher.ComputeHash(data);
hasher.Clear();
Someone wanna explain this one to me? :)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
虽然
Dipose()
方法是私有的,但如果将其转换为IDisposable
,您就可以获得对它的访问权限。 不过,正如其他人所说,Clear()
会为您调用它。然而,更好的方法是将变量的声明和赋值包含在 using() 块中:
While the
Dipose()
method is private, if you cast it toIDisposable
you can gain access to it. As others have said, though,Clear()
will call it for you.A better approach, however, is to enclose the declaration and and assignment of the variable in a using() block:
通过 Reflector 来看,
HashAlgorithm
的Clear
方法只是调用私有的Dispose
方法。 公开名为Clear
的方法的原因可能只是该类的设计者认为它是一个更适合哈希算法的名称。 您会在 BCL 的其他部分看到类似的样式,例如System.IO.Stream
的Close
。 另外,这里的最佳实践是使用using
块,它会在完成时自动调用私有Dispose
方法。Looking with Reflector, the
Clear
method ofHashAlgorithm
simply calls the privateDispose
method. The reason for exposing a method with nameClear
was probably just that the designers of the class thought it would be a more suitable name for a hash algorithm. You see similar styles within other parts of the BCL, such asClose
forSystem.IO.Stream
. Also, best practice here is to use ausing
block, which will automatically call the privateDispose
method when it's finished.你应该让 GC 为你处理这个问题。 这就是它的工作。
一些资源应该被处理,例如数据库连接和文件句柄,因此将它们放在
using
块中 (C#)。 不过,这不是其中之一。You should let the GC handle that for you. That's it's job.
Some resources should be disposed of, like DB connections and file handles, so put those in a
using
block (C#). This isn't one of those cases, though.