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
答案 0 :(得分:5)
您可以使用任务并行库而不是显式任务以及异步语言功能来轻松完成此任务:
private async void btnAddDirInput_Click(object sender, EventArgs e)
{
await Task.Run(() => getAllFiles(pathToSearch));
lable1.Text = "all done!";
}
答案 1 :(得分:3)
为什么不使用任务?
await Task.Run(() => getAllFiles(pathToSearch));
您的方法将在一个单独的线程上运行,释放您的主线程以保持UI响应。 任务完成后,控件将返回到您的UI线程。
修改:不要忘记将button_click方法标记为async void