0

I am trying to update the components on my form with blocking its thread.

My program uses DotNetZip to add files into an archive and I am trying to update the progress bars to illustrate the progress made.

The SaveProgress method is called when the Save() starts. Before and after each entry has been written and when the Save() is finished.

At the moment the labels are not being updated and the progressBar1 does not update?

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);
        }
    }
}
Saeb Amini
  • 23,054
  • 9
  • 78
  • 76
Peter
  • 11
  • 3
  • Use a background worker... http://www.dotnetperls.com/backgroundworker ... http://msdn.microsoft.com/en-us/library/cc221403%28v=vs.95%29.aspx?cs-save-lang=1&cs-lang=csharp#code-snippet-9 – Prix Oct 13 '14 at 05:14

1 Answers1

0

Compression is very CPU-intensive, of course it would freeze your UI thread, use a background thread for it instead:

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

Also since the SaveProgress event handler will now be called from the background thread, you have to change it to marshall UI updates to the UI thread.

Saeb Amini
  • 23,054
  • 9
  • 78
  • 76