You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何实现System.IO.Hashing中XxHash3算法的哈希进度上报?

实现System.IO.Hashing哈希计算的进度上报

要实现进度跟踪,核心是不能直接用Append(Stream)一次性处理整个文件,得手动分块读取文件流,每处理一块就更新进度。以下是针对XxHash3的实现代码:

private string GetXxHash3WithProgress(string filename, Action<long, long> progressCallback)
{
    var hashAlgorithm = new XxHash3();
    // 定义读取缓冲区大小,可根据需求调整,比如64KB
    const int bufferSize = 64 * 1024;
    var buffer = new byte[bufferSize];
    long totalBytes = new FileInfo(filename).Length;
    long processedBytes = 0;

    using (Stream entryStream = File.OpenRead(filename))
    {
        int bytesRead;
        while ((bytesRead = entryStream.Read(buffer, 0, bufferSize)) > 0)
        {
            hashAlgorithm.Append(buffer, 0, bytesRead);
            processedBytes += bytesRead;
            // 触发进度回调,传递已处理字节数和总字节数
            progressCallback?.Invoke(processedBytes, totalBytes);
        }
    }

    return BitConverter.ToString(hashAlgorithm.GetHashAndReset()).Replace("-", string.Empty);
}

使用示例

调用时传入进度处理逻辑,比如更新UI进度条或控制台输出:

var hash = GetXxHash3WithProgress("testfile.bin", (processed, total) =>
{
    double progressPercent = (double)processed / total * 100;
    // 这里可以更新UI,比如WinForms的progressBar.Value = (int)progressPercent;
    Console.WriteLine($"进度:{progressPercent:F2}%");
});

关键说明

  • 缓冲区大小可按需调整:太大可能占用更多内存,太小会增加回调次数,一般选64KB~1MB之间都可以
  • 如果涉及UI更新(比如WPF/WinForms),进度回调里需要切换到UI线程,避免跨线程异常
  • 算法类型不影响逻辑:换成System.IO.Hashing里的其他算法(比如Crc32、Blake2b),只需要把new XxHash3()改成对应实例即可

内容的提问来源于stack exchange,提问作者Raf-9600

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.28 11:32:10