使用sevenzipsharp进行C#解压缩并更新进度条而不冻结UI

时间:2017-04-10 16:20:19

标签: c# 7zip sevenzipsharp

我在文件提取方面遇到了一些问题。一切都适用于进度条输出和提取。但是当它运行时,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);
}

1 个答案:

答案 0 :(得分:1)

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

更新 - 以下是您查找示例的方式。我希望这能为您提供足够的理解,以便将来能够使用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));
    });
}