簡體   English   中英

使用sevenzipsharp提取C#並更新進度條,而無需凍結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>對象-它簡化了跨線程添加進度報告的過程。 這是一篇很好的博客文章,將BackgroundWorkerTask.Run()進行了比較 Task.Run()示例中看看他如何使用Progress<T>

更新 -這是您的示例的外觀。 希望這對您有足夠的了解,以后可以使用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));
    });
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM