2013-03-25 50 views
2

拋出我有以下代碼:異常由調用的目標BackgroundWorker的

public void extractZipFile() 
{ 
    if (!System.IO.Directory.Exists(extractDirectory)) 
     System.IO.Directory.CreateDirectory(extractDirectory); 

    BackgroundWorker worker = new BackgroundWorker(); 
    worker.WorkerReportsProgress = true; 
    worker.ProgressChanged += (o, e) => 
    { 
     progbarExtract.Value = Convert.ToInt32(e.ProgressPercentage); 
    }; 

    lblExtracting.Text = "Extracting..."; 
    worker.DoWork += (o, e) => 
    { 
     using (ZipFile zip = ZipFile.Read(zipFile)) 
     { 
      int step = Convert.ToInt32(zip.Count/100.0); 
      int percentComplete = 0; 
      foreach (ZipEntry file in zip) 
      { 
       file.Extract(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\XBMC Library Importer\\XBMC_Files", ExtractExistingFileAction.OverwriteSilently); 
        percentComplete += step; //When I comment this out I don't get an exception 
        worker.ReportProgress(percentComplete); 
      } 
     } 
    }; 

    worker.RunWorkerAsync(); 
} 

我不明白爲什麼聲明percentComplete += step;導致錯誤(Exception has been thrown by the target of an invocation.)。

我該如何解決這個問題?

另外,是否有人知道如何在提取完成後顯示消息框(MessageBox.Show())?

任何幫助,將不勝感激。

回答

3

您需要查看異常的InnerException屬性以瞭解TargetInvocationException的原因。

粗略猜測一下它:你計算的值步驟不正確。它應該是100.0/zip.Count。應該是雙倍的。因此,當.zip文件包含超過100個文件時,您可能會增加超過100的進度。當您將該值分配給ProgressBar.Value時,這將會炸彈。你應該注意到進度條在小檔案中行爲不當,從不增加。

調試這種難以捉摸的錯誤的好方法是調試+異常,勾選拋出複選框CLR異常。當拋出異常時,調試器現在停止。

+0

它在'Application.Run(new MainWindow());'在Program.cs – davidwroxy 2013-03-25 01:39:03

+0

中斷了哦,對不起,它實際上不在那裏。它在'progbarExtract.Value = Convert.ToInt32(e.ProgressPercentage);' – davidwroxy 2013-03-25 01:44:33

+0

這是我猜測的。請注意,ProgressPercentage大於100.我解釋了爲什麼,您的步驟值是錯誤的。 – 2013-03-25 02:15:33

0
worker.ProgressChanged += (o, e) => 
    { 

//看起來你正在綁定從後臺線程更新GUI元素,它拋出異常。嘗試編組線程到GUI線程。

progbarExtract.Value = Convert.ToInt32(e.ProgressPercentage); 
    }; 
+0

我很確定'ProgressChanged'處理程序是在原始GUI線程上調用的。 – LukeH 2013-03-25 01:09:33

相關問題