2017-04-10 121 views
0

我在解壓文件時遇到了一些問題。一切正常進展條輸出和提取。但是當它運行時,UI會凍結。我嘗試過使用Task.Run(),但是它並不能很好地處理進度條。或者,也許我只是沒有正確使用它。C#使用sevenzipsharp進行解壓縮並更新無UI凍結的進度欄

有什麼建議嗎?

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

您正在運行的主線程上的一切讓進度條工作要麼你需要使用後臺輔助類或展示如何使用進度對象創建自己的線程 – Krishna

回答

0

你可能想看看在.NET Framework中的Progress<T>對象 - 它簡化了添加進展跨線程報告。 Here is a good blog article comparing BackgroundWorker vs Task.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)); 
    }); 
} 
+0

謝謝! – Fredro