协助线程和等待表单完成

时间:2013-11-19 06:04:56

标签: c#

我有一个关于处理线程的问题。我正在将文件从一个文件夹复制到另一个文件夹,然后将它们压缩。问题是winform似乎试图在文件完成复制之前压缩文件,这反过来导致zip函数无法完成。我做了一些在这里环顾四周,说实话,我有问题包围我的工作原理。 MSDN有一个很好的小片段:

// Wait on a single task with no timeout specified.
        Task taskA = Task.Factory.StartNew(() => DoSomeWork(10000000));
        taskA.Wait();
        Console.WriteLine("taskA has completed.");


static void DoSomeWork(int val)
    {
        // Pretend to do something.
        Thread.SpinWait(val);
    }

再一次,我正试图等待完整的代码

error_handling("Daily Backup Started", "BackupLog.txt");
        string fileName = "";
        string Source = @"C:\folder\Program";
        string target = @"C:\folder\day_backup";
        string datestamp = DateTime.Now.ToString("MMddyy-HHmm");
        string[] files = System.IO.Directory.GetFiles(Source, "*.mdb");
        foreach (string file in files)
        {
            fileName = System.IO.Path.GetFileName(file);
            string destfile = System.IO.Path.Combine(target, fileName);
            System.IO.File.Copy(file, destfile);
            sub_error_handling(fileName+" has been copied", "DailyBackupLog.txt");
        }
        compression(@"C:\backupfolder\day_backup", @"\day_backup"+datestamp+".zip");
        sub_error_handling("Files were packaged for transmission", "DailyBackupLog.txt");

这里也是我的邮政编码:

private void compression(string zipdir, string zipfilename)
    {
        try
        {
            using (ZipFile zip = new ZipFile())
            {
                zip.AddDirectory(zipdir);
                zip.Comment = "This backup was created at " + System.DateTime.Now.ToString("G");
                zip.Save(zipdir + zipfilename);
            }
        }
        catch (Exception error)
        {
            error_handling("Incremental Backup Failed Compression was unsuccessful", "Incbackuplog.txt");
            sub_error_handling(error + "", "Incbackuplog.txt");
            error_handling("End Of Error Report", "Incbackuplog.txt");
        }
    }

它不会让我使用void来执行新任务,所以不确定还有什么可以尝试。有什么建议吗?

1 个答案:

答案 0 :(得分:0)

我会说这导致了挂起:

zip.AddDirectory(zipdir);
zip.Comment = "This backup was created at " + System.DateTime.Now.ToString("G");
zip.Save(zipdir + zipfilename);

您正在将zipdir中的所有文件压缩到同一位置的新文件中,以便新文件将包含在zip文件中。所以你试图将新文件包含在其中,这显然是不可能的,并且我认为解释为什么zip过程永远不会结束。

顺便说一句,您已将zipdir设置为与您的代码复制文件的目录不同的目录。