c# - 等到我的线程结束

标签 c# winforms

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

最佳答案

您可以使用任务并行库(而不是显式任务)以及异步语言功能来非常轻松地完成此任务:

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

关于c# - 等到我的线程结束,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18513205/

相关文章:

c# - 使用第三方 API 数据源绑定(bind)数据网格

c# - 生成串联的 SMS UDH 并将其添加到消息文本中

c# - 在哪些情况下应该使用某些类型的 IoC 框架

c# - DataTable Linq 连接多列

c# - 如何启动一个进程并使其主窗口成为启动进程窗口的模态?

c# - PictureBox 分配的 ErrorImage 在错误地处理其图像后未显示

c# - Visual Studio 设计器中的抽象通用 UserControl 继承

C#:如何将文本添加到字符串中的每一行?

c# - 多个 WebClient 不工作?

c# - 为什么 Task.ContinueWith 在此单元测试中执行失败?