简体   繁体   English

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

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

I'm having some problems with the file extraction. 我在提取文件时遇到了一些问题。 Everything works well with the progress bar output and the extraction. 进度条输出和提取都可以正常工作。 But when it is running the UI freezes. 但是在运行时,UI冻结。 I've tried to use Task.Run() but then it doesn't really work well with the progress bar. 我尝试使用Task.Run()但是它与进度条的配合并不是很好。 Or maybe I just didn't use it correctly. 也许我只是没有正确使用它。

Any suggestions? 有什么建议么?

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);
}

You may want to look into the Progress<T> object in the .NET Framework - it simplifies adding progress reporting across threads. 您可能需要查看.NET Framework中的Progress<T>对象-它简化了跨线程添加进度报告的过程。 Here is a good blog article comparing BackgroundWorker vs Task.Run() . 这是一篇很好的博客文章,将BackgroundWorkerTask.Run()进行了比较 Take a look at how he is using Progress<T> in the Task.Run() examples. Task.Run()示例中看看他如何使用Progress<T>

Update - Here is how it might look for your example. 更新 -这是您的示例的外观。 I hope this gives you a good enough understanding to be able to use the Progress<T> type in the future. 希望这对您有足够的了解,以后可以使用Progress<T>类型。 :D :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));
    });
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM