如何异步使用计算 MD5 哈希值?
我有这个代码:
static string CalculateMD5(string filename)
{
using (var md5 = MD5.Create())
{
using (var stream = File.OpenRead(filename))
{
var hash = md5.ComputeHash(stream);
return BitConverter.ToString(hash).Replace("-", "").ToUpperInvariant();
}
}
}
我想对 1GB 的文件进行哈希处理,然后它使我的应用程序卡住 20 秒。
最佳答案
当您从文件中读取时,您可以使用 IO 绑定(bind)异步性。不幸的是,File 类和 MD5 类都不支持开箱即用。但可以手动完成:
static async Task<string> CalculateMD5Async(string filename)
{
using (var md5 = System.Security.Cryptography.MD5.Create())
{
using (var stream = new FileStream(filename, FileMode.Open, FileAccess.Read, FileShare.Read, 4096, true)) // true means use IO async operations
{
byte[] buffer = new byte[4096];
int bytesRead;
do
{
bytesRead = await stream.ReadAsync(buffer, 0, 4096);
if (bytesRead > 0)
{
md5.TransformBlock(buffer, 0, bytesRead, null, 0);
}
} while (bytesRead > 0);
md5.TransformFinalBlock(buffer, 0, 0);
return BitConverter.ToString(md5.hash).Replace("-", "").ToUpperInvariant();
}
}
出于性能原因,您可能需要增加缓冲区大小。
关于c# - 如何异步MD5计算? C#,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49858310/