[英]How to create a System.Diagnostics.Process array
我想同時調用三個相同的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];
編譯失敗System.Diagnostics.Process p[] = new System.Diagnostics.Process()[3];
那么,我該如何解決呢?
您接近了,您必須刪除()
,然后為每個創建新的進程:
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() };
既創建數組又初始化元素。
據我了解,如果您稍微更改解決方案,它將完成您期望的一切。
我對您的解決方案進行了一些更改,並且工作正常。
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();
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.