如何停止长且不循环的C#进程
我有一个特定的情况,我有一个调用OS命令的进程,我需要停止或终止它。比如说,这是一个连续的过程。例如,该进程执行“myapplication.exe”。我不应该使用后台工作程序,而只是将其包装在线程中。那就杀了线?我还考虑过发送一个CTRL+C来取消,但不确定如何将其注入到进程命令中。正确的道路是什么如何停止长且不循环的C#进程,c#,thread-safety,backgroundworker,long-running-processes,C#,Thread Safety,Backgroundworker,Long Running Processes,我有一个特定的情况,我有一个调用OS命令的进程,我需要停止或终止它。比如说,这是一个连续的过程。例如,该进程执行“myapplication.exe”。我不应该使用后台工作程序,而只是将其包装在线程中。那就杀了线?我还考虑过发送一个CTRL+C来取消,但不确定如何将其注入到进程命令中。正确的道路是什么 private void btnExecuteResponseCmd_Click(object sender, EventArgs e) { backgroundWorker1.RunW
private void btnExecuteResponseCmd_Click(object sender, EventArgs e)
{
backgroundWorker1.RunWorkerAsync();
//https://stackoverflow.com/questions/4732737/how-to-stop-backgroundworker-correctly
//works if it is looping and can read the cancel variable but not in this case
}
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
ProcessStartInfo pStartInfo = new ProcessStartInfo("myapplication.exe");
//https://social.msdn.microsoft.com/Forums/en-US/5880a108-4169-44a5-81f2-6a745438d486/redirecting-command-window-messages-to-rich-text-box
pStartInfo.CreateNoWindow = true;
pStartInfo.UseShellExecute = false;
pStartInfo.RedirectStandardInput = true;
pStartInfo.RedirectStandardOutput = true;
pStartInfo.RedirectStandardError = true;
process1.OutputDataReceived += new DataReceivedEventHandler(OutputHandler);
process1.ErrorDataReceived += new DataReceivedEventHandler(ErrorHandler);
process1.StartInfo = pStartInfo;
process1.SynchronizingObject = rbResponse;
process1.Start();
process1.BeginOutputReadLine();
process1.WaitForExit();
}
好的,我找到了如何控制取消,看起来它很好地扼杀了这个过程。我将不得不探索它是否释放了所有资源,这是最好的方法
private void btnStopCommand_Click(object sender, EventArgs e)
{
process1.CancelOutputRead();
process1.Kill();
}
为什么要在cmd中执行ping,而不是直接在ping.exe中执行?为什么不使用process1.Kill()?为什么不在想要终止进程时使用process1.Kill(),而不是尝试发送CTRL+Cin而不是
process1.WaitForExit()
实现您自己的等待逻辑或检查OutputDataReceived
处理程序中的输出,并基于此停止/终止进程。你想做什么还不完全清楚。您也可以使用process1.WaitForExit(timeInMs)
。^^如果检测到取消,您当然可以发送信号/终止它。完全不同的方法当然是“它真的需要是cmd吗?”