C# 使用 sevenzipsharp 提取并更新进度条而不 UI 冻结

C# extracting with sevenzipsharp and update progress bar without UI freeze

我在提取文件时遇到了一些问题。一切都适用于进度条输出和提取。但是当它是 运行 时 UI 冻结。我试过使用 Task.Run() 但它在进度条上效果不佳。或者我只是没有正确使用它。

有什么建议吗?

private void unzip(string path)
{
    this.progressBar1.Minimum = 0;
    this.progressBar1.Maximum = 100;
    progressBar1.Value = 0;
    this.progressBar1.Visible = true;
    var sevenZipPath = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), Environment.Is64BitProcess ? "x64" : "x86", "7z.dll");
    SevenZipBase.SetLibraryPath(sevenZipPath);

    var file = new SevenZipExtractor(path + @"\temp.zip");
    file.Extracting += (sender, args) =>
        {
            this.progressBar1.Value = args.PercentDone; 
        };
    file.ExtractionFinished += (sender, args) =>
        {
            // Do stuff when done
        };


    //Extract the stuff
    file.ExtractArchive(path);
}

您可能需要查看 .NET Framework 中的 Progress<T> 对象 - 它简化了跨线程添加进度报告。 Here is a good blog article comparing BackgroundWorker vs Task.Run()。看看他在 Task.Run() 示例中如何使用 Progress<T>

Update - 以下是您的示例的外观。我希望这能让你有足够的理解,以便将来能够使用 Progress<T> 类型。 :D

private void unzip(string path)
{
    progressBar1.Minimum = 0;
    progressBar1.Maximum = 100;
    progressBar1.Value = 0;
    progressBar1.Visible = true;

    var progressHandler = new Progress<byte>(
        percentDone => progressBar1.Value = percentDone);
    var progress = progressHandler as IProgress<byte>;

    Task.Run(() =>
    {
        var sevenZipPath = Path.Combine(
            Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location),
            Environment.Is64BitProcess ? "x64" : "x86", "7z.dll");

        SevenZipBase.SetLibraryPath(sevenZipPath);


        var file = new SevenZipExtractor(path);
        file.Extracting += (sender, args) =>
        {
            progress.Report(args.PercentDone);
        };
        file.ExtractionFinished += (sender, args) =>
        {
            // Do stuff when done
        };

        //Extract the stuff
        file.ExtractArchive(Path.GetDirectoryName(path));
    });
}