0

How can i catch my process id when the event raised ?

 Process pros = Process.Start(ProcessStartInfo);
 pros.EnableRaisingEvents = true;
 pros.Exited += pros_Exited;

private void pros_Exited(object sender, EventArgs e)
{
    int processId = ??
}
user1860934
  • 417
  • 2
  • 9
  • 22

1 Answers1

3

You can use an anonymous function the captures the Process variable:

Process pros = Process.Start(processStartInfo);
pros.EnableRaisingEvents = true;
pros.Exited += (object sender, EventArgs e) =>
{
    int processId = pros.Id;
    // ...
};

Edit: If you intend to use the above notation in a loop, make sure that you understand closures.

foreach (Process process in myProcesses)
{
    process.EnableRaisingEvents = true;
    Process processInner = process;   // copy to inner variable
    processInner.Exited += (object sender, EventArgs e) =>
    {
        int processId = processInner.Id;   // always reference inner variable
        // ...
    };
}
Community
  • 1
  • 1
Douglas
  • 53,759
  • 13
  • 140
  • 188
  • something is confusing me about this answer.. does it imply that a process id is somehow different when it exits than when it starts? if not, then what would be the purpose of code like this? – Aaron Anodide Sep 21 '13 at 20:59
  • @AaronAnodide: No, the process ID [doesn't change](http://msdn.microsoft.com/en-us/library/system.diagnostics.process.id.aspx): "Until the process terminates, the process identifier uniquely identifies the process throughout the system." You can read its value as soon as the process is launched. The purpose of this code is to show how to use this ID once the process terminates. – Douglas Sep 21 '13 at 21:33
  • then why not use ((Process)sender).Id? Bringing in the issue of closures here seems like overkill (to me - maybe there's something I don't understand which is the only reason I am commenting) – Aaron Anodide Sep 21 '13 at 22:00
  • I didn't use `sender` because it [isn't documented](http://msdn.microsoft.com/en-us/library/system.diagnostics.process.exited.aspx) to correspond to the terminated `Process` instance (although it empirically does). Besides, the anonymous function results in even conciser code than the traditional event handler. The closure issue only applies when using loops. – Douglas Sep 21 '13 at 22:21