簡體   English   中英

等到我的線程完成

[英]Wait until my thread is finished

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!";
}

為什么不使用任務?

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

您的方法將在單獨的線程上運行,從而釋放主線程以保持UI響應。 任務完成后,控件將返回到您的UI線程。

編輯:別忘了將您的button_click方法標記為async void

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM