Kyle
Kyle

Reputation: 3042

DotNetZip freezing my application?

            string desktop = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);    
            public void unzip(String zFile)
            {
                Ionic.Zip.ZipFile zip = Ionic.Zip.ZipFile.Read(zFile);
                zip.ExtractProgress += new EventHandler<ExtractProgressEventArgs>(zip_ExtractProgress);
                zip.ExtractAll(desktop + "\\cache", ExtractExistingFileAction.OverwriteSilently);
                zip.Dispose();
                zip = null;
            }

            void zip_ExtractProgress(object sender, ExtractProgressEventArgs e)
            {

                if (e.EventType == ZipProgressEventType.Extracting_EntryBytesWritten)
                {
                    label2.Text = "debug: " + ((e.EntriesExtracted));
                }
                else if (e.EventType == ZipProgressEventType.Extracting_BeforeExtractEntry)
                {
                    label3.Text = e.CurrentEntry.FileName;
                }
            }

            private void button1_Click(object sender, EventArgs e)
            {
                unzip(desktop + "\\cache.zip");
            }

When I execute the unzip button1_Click() my application freezes. I'm new to C# and I'm not really sure how to fix this, can someone help me?

Upvotes: 1

Views: 1559

Answers (3)

tomfanning
tomfanning

Reputation: 9660

Long running blocking operations should not run on the main UI thread, since as you can see the UI will freeze up.

Consider using a BackgroundWorker to do the work on a separate thread.

There's a good summary here.

Report progress back to the UI by handling the ProgressChanged event and calling backgroundWorker.ReportProgress(), rather than directly updating label2.Text from inside there.

i.e. from inside your zip_ExtractProgress method, call backgroundWorker.ReportProgress

Upvotes: 3

Hans Passant
Hans Passant

Reputation: 941615

 label3.Text = e.CurrentEntry.FileName;
 label3.Update();

The Update() method ensures that the label is painted, now showing the Text property you assigned. Without it, the painting doesn't happen until the unzipping code stops running and your program goes idle again. Otherwise known as 'pumping the message loop'. Calling Update() is only a partial fix, your window is still catatonic and won't respond to mouse clicks for example. If it takes longer than a couple of seconds, Windows displays the "Not responding" ghost window.

Get some experience with coding in C#, then tackle threading with the BackgroundWorker class.

Upvotes: 2

Jim Brissom
Jim Brissom

Reputation: 32929

Easiest way: Execute the unzip method using a BackgroundWorker. Be sure to modify GUI controls only on the main GUI thread, by using Invoke.

Upvotes: 1

Related Questions