Search code examples
c#exit-codesystem.diagnostics

How to create a System.Diagnostics.Process array


I want to call three of the same EXE at the same time, and I expect three return value when they all terminated, Here's how I got so far:

    System.Diagnostics.Process p = new System.Diagnostics.Process();
    p.StartInfo.FileName = MyEXEPath;
    for(int i=0;i<3;i++)
    {
       p.StartInfo.Arguments =  para1[i] + " " + para2[i];
       p.Start();
       Console.WriteLine("Start run");
    }
    p.WaitForExit();
    int result = p.ExitCode;
    Console.WriteLine("Return info:" + results);  //Problem: I can only get the last return value

You can see I only got one return value, not three, so I wonder if I can do this:

    int[] results = new int[3];
    System.Diagnostics.Process p[] = new System.Diagnostics.Process()[3];
    for(int i=0;i<3;i++)
    {
       p[i].StartInfo.FileName = MyEXEPath;
       p[i].StartInfo.Arguments = para1[i] + " " + para2[i];
       p[i].Start();
       Console.WriteLine("Start run");
       p[i].EnableRaisingEvents = true;
       p[i].Exited += (sender, e) =>
       {
          results[i] = p[i].ExitCode;
          Console.WriteLine("Return info:" + results[i]);
       };
    }
    while(results[0] != 0 && results[1] != 0 && results[2] != 0 )
    {
        break;  //all EXEs ternimated,  break and continue my job
    }

Sure it is compile fail with System.Diagnostics.Process p[] = new System.Diagnostics.Process()[3]; So how can I fixed it or there's another way?


Solution

  • You are close, you would have to remove the () and then create new process for each one:

    System.Diagnostics.Process[] p = new System.Diagnostics.Process[3];
    p[0] = new System.Diagnostics.Process();
    p[1] = new System.Diagnostics.Process();
    p[2] = new System.Diagnostics.Process();
    

    Alternatively, you can use a C# array initializer and short-hand (implicit array initialization). In the following code I would use a using System.Diagnostics; at the top of the file to reduce the namespace:

    var p = new [] { new Process(), new Process(), new Process() };
    

    Which both creates the array and initializes the elements.