如何异步MD5计算? C#

时间:2018-04-16 13:17:52

标签: c# .net hash

如何使用计算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秒。

2 个答案:

答案 0 :(得分:1)

试试这个:

 private async void CalculateMd5_Click(object sender, EventArgs e)
    {
        var filePath = "Path/to/your/file";
        var md5hash = await CalculateMd5ForFileAsync(filePath);
    }

    private Task<string> CalculateMd5ForFileAsync(string filePath)
    {
        return new Task<string>(() => ComputeMd5HashForFile(filePath));
    }

    private string ComputeMd5HashForFile(string filePath)
    {
        using (var md5 = MD5.Create())
        {
            using (var stream = File.OpenRead(filePath))
            {
                var hash = md5.ComputeHash(stream);
                return BitConverter.ToString(hash).Replace("-", "").ToUpperInvariant();
            }
        }
    }

答案 1 :(得分:1)

当您从文件中读取时,您可以使用IO绑定的异步性。不幸的是,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();
    }
  }

出于性能原因,您可能希望增加缓冲区大小。