7

バックグラウンドで実行されるプロセスがWaitForExit()あり、期間は異なる場合があり、終了するまで待つ必要があるためです。場合によっては、完了する前に終了する必要があり.Kill()、クラス イベントを介してコマンドをトリガーします。プロパティは.HasExitedtrue に変更されますが、コードが通過することはありません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た。私のアプリではプロセスを早期に終了することはめったにありませんが、それでも機能させる必要があるため、この実装で行う必要があります。

}

4

2 に答える 2

0

よりクリーンなコードを試していただけますか (私は思います)。テスト済み.....

Process proc = null;

//Kill process after 3 seconds
Task.Run(() =>
{
    Task.Delay(3000).Wait();

    if(proc!=null && proc.HasExited==false) proc.Kill();
});


var psi = new ProcessStartInfo()
{
    FileName = "ping.exe",
    Arguments = "-t 127.0.0.1",
    RedirectStandardOutput = true,
    UseShellExecute = false,
    CreateNoWindow = true,
};

proc = new Process();
proc.StartInfo = psi;
proc.OutputDataReceived += (s,e) =>
{
    Console.WriteLine(e.Data);
};

proc.Start();
proc.BeginOutputReadLine();
proc.WaitForExit();

Console.WriteLine("**killed**");
于 2013-09-09T21:55:59.507 に答える