C#更新进度条而不阻塞表单线程

时间:2014-10-13 05:12:16

标签: c# dotnetzip

我正在尝试通过阻止其线程来更新表单上的组件。

我的程序使用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);
        }
    }
}

1 个答案:

答案 0 :(得分: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更新。