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 を更新したい

4

2 に答える 2

3

タスクを使用しないのはなぜですか?

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

メソッドは別のスレッドで実行され、メイン スレッドを解放して UI の応答性を維持します。タスクが完了するとすぐに、コントロールは UI スレッドに戻ります。

編集:button_clickメソッドを次のようにマークすることを忘れないでくださいasync void

于 2013-08-29T14:25:12.897 に答える