2013-08-29 29 views
1
public delegate void FileEventHandler(string file); 
public event FileEventHandler fileEvent; 

public void getAllFiles(string path) 
{ 
    foreach (string item in Directory.GetDirectories(path)) 
    { 
     try 
     { 
      getAllFiles(item); 
     } 
     catch (Exception) 
     { } 
    } 

    foreach (string str in Directory.GetFiles(path, "*.pcap")) 
    { 
     // process my file and if this file format OK raised event to UI and add the file to my listbox 
     FileChecker fileChecker = new FileChecker(); 
     string result = fileChecker.checkFIle(str); 
     if (result != null) 
      fileEvent(result); 
    } 
} 

private void btnAddDirInput_Click(object sender, EventArgs e) 
{ 
     ThreadStart ts = delegate { getAllFiles(pathToSearch); }; 
     Thread thread = new Thread(ts); 
     thread.IsBackground = true; 
     thread.Start(); 
} 

我想等到线程完成自己的工作,然后更新我的UI等到我的线程完成

+10

你的线程在哪里? – CodingIntrigue

+2

http://stackoverflow.com/questions/1584062/how-to-wait-for-thread-to-finish-with-net?rq=1检查出来 – Nick

+0

我通过邮件中的另一个线程调用getAllFiles() UI – user2214609

回答

5

您可以使用任务并行库,而不是明确的任务,与异步语言功能一起做到这一点很容易:

private async void btnAddDirInput_Click(object sender, EventArgs e) 
{ 
    await Task.Run(() => getAllFiles(pathToSearch)); 
    lable1.Text = "all done!"; 
} 
+0

如果这在一个单独的线程运行,文本属性分配会抛出一个运行时异常。 –

+0

@JonathanHenson看看这个方法。这是按钮点击事件处理程序。它在UI线程中运行。 – Servy

+0

抱歉没有注意到。等待不会阻止UI线程? –

3

为什么不使用任务?

await Task.Run(() => getAllFiles(pathToSearch)); 

您的方法将在单独的线程上运行,释放您的主线程以保持UI响应。 只要任务完成,控件就会返回到您的UI线程。

编辑:别忘了标记您button_click方法async void

+0

只是好奇,是否有可能以这种方式更新进度栏? – Koryu

+0

@Koryu你可以使用'Progress'类来更新进度条。 – Servy

+0

你的意思是运行定期更新进度条的任务吗?你可以,但我不认为任务是为此目的而设计的。 – dcastro