【发布时间】:2019-06-23 18:06:22
【问题描述】:
我在后台工作人员的 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();
我为我的工作人员添加了取消支持,我希望它在我按下按钮后退出。由于工作人员实际上是进程本身,并且进程在活动时不断发送输出,因此我试图找到一种方法来从 OutputDataReceived 终止/杀死/停止它。上面的代码似乎成功地终止了进程(它不再发送调试输出),但由于某种原因,工作者的完成事件从未被触发,应用程序在那里停止。
【问题讨论】:
-
其实这更荒谬。当然,它奏效了。我不仅在按下按钮时运行 CancelAsync,还终止了进程本身。 worker_completed 方法现在正常触发,我可以使用 e.Cancel 显示信息。您可以做出回答,以便我为您投票。谢谢
-
您实际上可以自己回答自己的问题。这样做在 StackOverflow 上并不少见,当然也不会受到反对。因此,如果您愿意,请回答;-)(仅供参考:OutputDataReceived 处理程序中的 WaitForExit 不仅是多余的,而且没有目的)
-
我会回答的,谢谢。关于 WaitForExit,如果我没有把它放在那里,我会收到拒绝访问错误并且应用程序崩溃了。根据 MS 的 Kill() 文档,建议在 Kill() 之后运行 WaitForExit
-
这很好奇。您已经在处理程序之外拥有 WaitForExit (我猜是后台工作线程正在执行的方法的一部分)。嗯,也许从处理程序中调用 Kill 会使某些句柄/资源处于无效状态,直到操作系统开始实际杀死和清理进程,当处理程序返回到 Process 类中的调用代码时,使 Process 类行为异常。直到... ;-)
标签: c# process backgroundworker