【问题标题】:How to create a System.Diagnostics.Process array如何创建 System.Diagnostics.Process 数组
【发布时间】:2018-04-11 03:56:52
【问题描述】:

我想同时调用三个相同的 EXE,当它们都终止时,我期望三个返回值,这是我到目前为止的结果:

    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

你可以看到我只有一个返回值,而不是三个,所以我想知道我是否可以这样做:

    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
    }

确定编译失败,System.Diagnostics.Process p[] = new System.Diagnostics.Process()[3]; 那么我该如何解决它或有其他方法?

【问题讨论】:

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

标签: c# exit-code system.diagnostics


【解决方案1】:

您已经很接近了,您必须删除(),然后为每个进程创建新进程:

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();

或者,您可以使用 C# 数组初始化程序和速记(隐式数组初始化)。在以下代码中,我将在文件顶部使用 using System.Diagnostics; 来减少命名空间:

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

既创建数组又初始化元素。

【讨论】:

    【解决方案2】:

    据我了解,如果您稍微更改一下您的解决方案,它会按照您的预期进行。

    我对您的解决方案进行了一些更改,它工作正常。

    static void Main(string[] args)
    {
        System.Diagnostics.Process p = new System.Diagnostics.Process();
        p.StartInfo.FileName = "notepad.exe";
        for (int i = 0; i < 3; i++)
        {
            p.StartInfo.Arguments = $"d:\\text{i}.txt";
            p.Start();
            Console.WriteLine("Start run");
            p.WaitForExit();
            int result = p.ExitCode;
            Console.WriteLine("Return info:" + $"text{i}.txt created successfully!");
        }
    
        p.StartInfo.FileName = "explorer.exe";
        p.StartInfo.Arguments = "d:";
        p.Start();
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-08-23
      • 2013-06-16
      • 2010-10-13
      • 1970-01-01
      • 2011-02-02
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多