调用Directory.EnumerateFiles的BackgroundWorker在枚举完成之前完成

时间:2013-07-17 20:49:03

标签: c# backgroundworker .net

似乎是一个微不足道的问题。

我有以下代码段。似乎已完成的事件在EnumerateFiles实际完成之前触发。例如,如果将类似C:\users\<user>\desktop的路径的tb_source.Text ...设置为包含大约一百件项目的文件夹,则所有作品和reference.throttler_numer_of_files都会正确填充。

看起来,如果我设置说,C:\users\<user>它永远不会有机会找到所有内容,然后再转到已完成的事件。也许在尝试计算文件时遇到异常?

Suggesetions?

// count number of files within source directory (and within subdirectories)
BackgroundWorker bw = new BackgroundWorker();
bw.WorkerReportsProgress = true;

bw.DoWork += new DoWorkEventHandler(
    delegate(object o, DoWorkEventArgs args)
    {
        Thread.Sleep(2000); // give the current UI a moment to load
        reference.throttler_number_of_files = Directory.EnumerateFiles(tb_source.Text, "*.*", SearchOption.AllDirectories).Count();
    }
);

bw.RunWorkerCompleted += new RunWorkerCompletedEventHandler(
    delegate(object o, RunWorkerCompletedEventArgs args)
    {
        // success, clear to launch!
        form_throttler_copy throttler_copy = new form_throttler_copy();
        throttler_copy.Show();
        this.Dispose();
    }
);

label_status.Text = "Creating manifest of files... please wait";
picturebox_loading.Visible = true;

bw.RunWorkerAsync();

1 个答案:

答案 0 :(得分:0)

原来问题是EnumerateFiles期间出现异常(访问被拒绝)错误。我能够捕获异常,但现在我必须确定一个好的方法,我可以继续枚举,使其转移到下一个文件/目录。

编辑 - 供将来参考,此处的详细信息有助于如何执行上述操作: Directory.EnumerateFiles => UnauthorizedAccessException