2014-10-13 55 views
0

我想通過阻塞其線程來更新我的窗體上的組件。C#更新沒有阻塞表單線程的進度條

我的程序使用DotNetZip將文件添加到檔案中,我試圖更新進度條來說明所取得的進展。

Save()開始時調用SaveProgress方法。每個條目寫入之前和之後以及Save()完成時。

目前標籤沒有被更新並且progressBar1沒有更新?

private void buttonCompress_Click(object sender, EventArgs e) 
{ 
    if ((folderBrowserDialog1.ShowDialog() == DialogResult.OK) && (saveFileDialog1.ShowDialog() == DialogResult.OK)) 
    { 
     buttonCompress.Enabled = false; 

     String DirectoryToZip = folderBrowserDialog1.SelectedPath; 
     String ZipFileToCreate = saveFileDialog1.FileName; 

     using (ZipFile zip = new ZipFile()) 
     { 
      zip.CompressionLevel = Ionic.Zlib.CompressionLevel.Default; 
      zip.SaveProgress += SaveProgress; 

      zip.StatusMessageTextWriter = System.Console.Out; 
      zip.AddDirectory(DirectoryToZip); // recurses subdirectories 
      zip.Save(ZipFileToCreate); 
     } 
    } 
} 
+0

使用後臺工作人員... http://www.dotnetperls.com/backgroundworker ... http://msdn.microsoft.com/en-us/library/cc221403%28v=vs.95%29。 ASPX?CS-保存琅= 1&CS琅= CSHARP#代碼片斷-9- – Prix

回答

0

壓縮是CPU密集型的,當然它會凍結你的UI線程,使用一個後臺線程它來代替:

private void buttonCompress_Click(object sender, EventArgs e) 
{ 
    if ((folderBrowserDialog1.ShowDialog() == DialogResult.OK) && (saveFileDialog1.ShowDialog() == DialogResult.OK)) 
    { 
     buttonCompress.Enabled = false; 

     String DirectoryToZip = folderBrowserDialog1.SelectedPath; 
     String ZipFileToCreate = saveFileDialog1.FileName; 

     // fire off zipping job in a background thread 
     Task.Factory.StartNew(() => StartZipping(DirectoryToZip, ZipFileToCreate), TaskCreationOptions.LongRunning); 
    } 
} 

private object StartZipping(string DirectoryToZip, string ZipFileToCreate) 
{ 
    using (ZipFile zip = new ZipFile()) 
    { 
     zip.CompressionLevel = Ionic.Zlib.CompressionLevel.Default; 
     zip.SaveProgress += SaveProgress; 

     zip.StatusMessageTextWriter = System.Console.Out; 
     zip.AddDirectory(DirectoryToZip); // recurses subdirectories 
     zip.Save(ZipFileToCreate); 
    } 
} 

而且由於SaveProgress事件處理程序現在將來自被叫後臺線程,你必須將其更改爲UI UI線程的UI更新。