簡體   English   中英

如何停止一個很長且不循環的 C# 進程

[英]How to stop a C# Process that is long and does not loop

我有一個特定的情況,我有一個調用 OS 命令的進程,我需要停止或終止它。 例如,假設它是一個連續的過程。 例如,該進程執行了“myapplication.exe”。 我是否應該不使用后台工作程序而將其包裝在一個線程中。 然后殺死線程? 我還考慮過發送 CTRL+C 來取消,但不確定如何將其注入到進程命令中。 什么是正確的道路?

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();
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM