バックグラウンドで実行されるプロセスがWaitForExit()
あり、期間は異なる場合があり、終了するまで待つ必要があるためです。場合によっては、完了する前に終了する必要があり.Kill()
、クラス イベントを介してコマンドをトリガーします。プロパティは.HasExited
true に変更されますが、コードが通過することはありませんWaitForExit()
。
public class MyProcess: Process
{
private bool exited;
public MyProcess()
{
...
}
public void Start(args...)
{
try
{
base.StartInfo.FileName = ...
base.StartInfo.Arguments = ...
base.StartInfo.RedirectStandardOutput = true;
base.StartInfo.UseShellExecute = false;
base.StartInfo.CreateNoWindow = true;
base.EnableRaisingEvents = true;
base.Exited += new EventHandler(MyProcessCompleted);
base.OutputDataReceived += new DataReceivedEventHandler(outputReceived);
base.Start();
this.exited = false;
base.BeginOutputReadLine();
while (!this.exited)
{
if ()
{
...
}
else
{
base.WaitForExit(); ---- after the process is killed, it never gets past this line.
}
...
}
}
catch (Exception ex)
{
...
}
}
private void MyProcessCompleted(object sender, System.EventArgs e)
{
exited = true;
...
}
private void outputReceived(object sender, DataReceivedEventArgs e)
{
...
}
//Subscription to cancel event
public void ProcessCanceled(object sender, EventArgs e)
{
...
if (!exited)
{
base.Kill();
}
}
}
\
アップデート:
私のプロセスは Java ベースのファイル転送クライアントを起動し、転送を実行します。プロセスはタスク マネージャーに表示され、Kill()
終了しません。プロセスを終了することはあまり気にせず、プログラムが次の「タスク」に進む必要があるため、 のClose()
直後にKill()
を追加しましWaitForExit
た。私のアプリではプロセスを早期に終了することはめったにありませんが、それでも機能させる必要があるため、この実装で行う必要があります。
}