閑古鳥

オールドプログラマの日記。プログラミングとか病気(透析)の話とか。

別プロセスの実行結果を逐次取得する

非同期でfindstrを実行する文字列検索ツールの作成:CodeZine

別プロセス(findstr)の実効結果をリアルタイムにリストボックスに追加するためにデリゲートを使用していますが、これは大げさなような(例として使いやすかったから使っているだけでしょうが)。

このくらいの用途なら同期処理でもなんとかなります。

Process findProcess = new System.Diagnostics.Process();
findProcess.StartInfo.UseShellExecute = false;
findProcess.StartInfo.RedirectStandardOutput = true;
findProcess.StartInfo.CreateNoWindow = true;
findProcess.StartInfo.FileName = "findstr.exe";
findProcess.StartInfo.Arguments = "/N \"" + findstr + "\" " + searchfiles;
findProcess.EnableRaisingEvents = true; // Process.Exitedイベントを発生させる

bool exit = false;
findProcess.Exited += delegate { exit = true; };
stopButton.Click += delegate { exit = true; };

findProcess.Start();

while (!exit)
{
    string line = findProcess.StandardOutput.ReadLine();
    if (line != null)
    {
        resultList.Items.Add(line);
        resultList.Refresh();
    }
    Application.DoEvents();
}

findProcess.Dispose();