为什么我的进程的Exited方法没有被调用?


96

我有以下代码,但是为什么ProcessExited从未调用该方法?如果我不使用Windows shell(startInfo.UseShellExecute = false),则相同。

ProcessStartInfo startInfo = new ProcessStartInfo();
startInfo.CreateNoWindow = true;
startInfo.UseShellExecute = true;
startInfo.WindowStyle = ProcessWindowStyle.Hidden;
startInfo.FileName = path;
startInfo.Arguments = rawDataFileName;
startInfo.WorkingDirectory = Util.GetParentDirectory(path, 1);

try
{
     Process correctionProcess = Process.Start(startInfo);
     correctionProcess.Exited += new EventHandler(ProcessExited);                   

     correctionProcess.WaitForExit();

     status = true;
}

.....

internal void ProcessExited(object sender, System.EventArgs e)
{
      //print out here
}

Answers:


241

为了接收Exited事件的回调,EnableRaisingEvents必须将true设置为true。

Process correctionProcess = Process.Start(startInfo);
correctionProcess.EnableRaisingEvents = true;
correctionProcess.Exited += new EventHandler(ProcessExited); 

3
CorrectionProcess.WaitForExit(),如果没有此功能,此代码
Kira 2016年

7
一个小技巧(对于非C#专家尤其如此):不要执行Close()此过程!由于在资源管理上的误导,我遇到了Exit处理程序间歇性的问题。有问题的代码调用Process.Close()after Process.Start(startInfo),而不是允许GC在适当的时候进行收集。如果您的背景是非GC语言(例如C / C ++),则很容易犯错误。
Jerzy

3
大。谢谢。我也想谈谈的是分配EnableRaisingEventsEventHandlers必须之后,恰好完成Process.Start()。否则它将无法正常工作。
Doruk '16

2
@Doruk我可以EnableRaisingEvents=true在致电之前进行设置,Process.Start()并且效果很好。
Action Dan

29

MSDN

Exited事件指示关联的进程已退出。发生这种情况意味着该进程终止(中止)或成功关闭。仅当EnableRaisingEvents属性的值为true时,才会发生此事件。

您是否将该属性设置为true?


19
这也是一个非常无主位的标志(无论如何使用,如果我不想参加此活动,我不订阅它!)
TamásSzelei 2014年

3
不是很直观。在每个事件描述中应清楚说明需要设置此标志。
TheLegendaryCopyCoder



9

我遇到的例子那个地方new Process()一个在using条款。如果要使用该Exited功能,请不要这样做。该using条款对任何事件句柄沿着破坏实例Exited

这个...

using(var process = new Process())
{
   // your logic here
}

应该是这个...

var process = new Process();

我也注意到了。奇怪的是,OutputDataReceived事件可以正常工作。或者它们发生的速度如此之快,以至于在主线程中执行之前就结束了使用。
AlexVB
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.