在后台工作人员中杀死外部进程
Killing external process inside background worker
我将此代码放在后台工作人员的 DoWork 中:
Process downloadConvert = new Process();
downloadConvert.StartInfo.FileName = @"process.exe";
downloadConvert.StartInfo.Arguments = "args here";
downloadConvert.StartInfo.UseShellExecute = false;
downloadConvert.StartInfo.RedirectStandardOutput = true;
downloadConvert.StartInfo.RedirectStandardError = true;
downloadConvert.StartInfo.CreateNoWindow = true;
downloadConvert.EnableRaisingEvents = true;
downloadConvert.OutputDataReceived += (s, er) =>
{
Debug.WriteLine(er.Data);
if (er.Data != null && er.Data != "")
{
metadata trackInfo = JsonConvert.DeserializeObject<metadata>(er.Data);
title.Add(trackInfo.title);
}
if (fetchInfoBW.CancellationPending == true)
{
e.Cancel = true;
downloadConvert.Kill();
downloadConvert.WaitForExit();
return;
}
};
downloadConvert.Start();
downloadConvert.BeginOutputReadLine();
downloadConvert.WaitForExit();
我已经为我的工作人员添加了取消支持,我希望它在我按下按钮后退出。由于 worker 实际上是进程本身,并且进程在活动时不断发送输出,所以我试图找到一种从 OutputDataReceived 中 terminate/kill/stop 它的方法。上面的代码似乎成功地终止了进程(它不再发送调试输出)但由于某种原因,工作人员的完成事件从未被触发并且应用程序在那里停止。
解决方案是全局声明进程,然后在本地初始化它。这样它在整个应用程序中都是可见的,并且我能够在按下按钮时将其杀死,同时我也在调用 worker 上的 CancelAsync() 方法。
我将此代码放在后台工作人员的 DoWork 中:
Process downloadConvert = new Process();
downloadConvert.StartInfo.FileName = @"process.exe";
downloadConvert.StartInfo.Arguments = "args here";
downloadConvert.StartInfo.UseShellExecute = false;
downloadConvert.StartInfo.RedirectStandardOutput = true;
downloadConvert.StartInfo.RedirectStandardError = true;
downloadConvert.StartInfo.CreateNoWindow = true;
downloadConvert.EnableRaisingEvents = true;
downloadConvert.OutputDataReceived += (s, er) =>
{
Debug.WriteLine(er.Data);
if (er.Data != null && er.Data != "")
{
metadata trackInfo = JsonConvert.DeserializeObject<metadata>(er.Data);
title.Add(trackInfo.title);
}
if (fetchInfoBW.CancellationPending == true)
{
e.Cancel = true;
downloadConvert.Kill();
downloadConvert.WaitForExit();
return;
}
};
downloadConvert.Start();
downloadConvert.BeginOutputReadLine();
downloadConvert.WaitForExit();
我已经为我的工作人员添加了取消支持,我希望它在我按下按钮后退出。由于 worker 实际上是进程本身,并且进程在活动时不断发送输出,所以我试图找到一种从 OutputDataReceived 中 terminate/kill/stop 它的方法。上面的代码似乎成功地终止了进程(它不再发送调试输出)但由于某种原因,工作人员的完成事件从未被触发并且应用程序在那里停止。
解决方案是全局声明进程,然后在本地初始化它。这样它在整个应用程序中都是可见的,并且我能够在按下按钮时将其杀死,同时我也在调用 worker 上的 CancelAsync() 方法。