我已经编写了一个小程序(ProcessSample)来启动在.txt文件中定义的另一个程序(以换行符分隔)。立即启动多个程序
代码大部分来自MSDN。我刚开始我的编程冒险,但我想写一些有用的东西。
我不知道从我的ProcessSample程序同时运行两个程序的智能方法。
在我的.txt文件中,我只是使用.exe程序的路径。这一切工作正常,但我的程序当时只运行一个程序。我以为我会运行foreach,但当然它不会在这里工作,因为它只运行第一个程序,它会等到我退出时才会运行下一个程序。
所以我知道它不工作的原因。我只是想知道如何让它按我想要的方式工作。
我的C#代码:
using System;
using System.Diagnostics;
using System.Threading;
namespace ProcessSample
{
class ProcessMonitorSample
{
public static void Main()
{
Console.BufferHeight = 25;
// Define variables to track the peak memory usage of the process.
long peakWorkingSet = 0;
string[] Programs = System.IO.File.ReadAllLines(@"C:\Programs\list.txt");
foreach (string Program in Programs)
{
Process myProcess = null;
// Start the process.
myProcess = Process.Start(@Program);
// Display the process statistics until
// the user closes the program.
do
{
if (!myProcess.HasExited)
{
// Refresh the current process property values.
myProcess.Refresh();
// Display current process statistics.
Console.WriteLine();
Console.WriteLine("Path: {0}, RAM: {1}", Program, (myProcess.WorkingSet64/1024/1024));
// Update the values for the overall peak memory statistics.
peakWorkingSet = myProcess.PeakWorkingSet64;
if (myProcess.Responding)
{
Console.WriteLine("Status: Running");
}
else
{
Console.WriteLine("Status: Not Responding!");
}
// Wait 2 seconds
Thread.Sleep(2000);
} // if
} // do
while (!myProcess.WaitForExit(1000));
Console.WriteLine();
Console.WriteLine("Process exit code: {0}", myProcess.ExitCode);
Console.WriteLine("Peak physical memory usage of the process: {0}", (peakWorkingSet/1024/1024));
Console.WriteLine("Press any key to exit.");
System.Console.ReadKey();
} // foreach
} // public
} //class
} // namespace
如果程序已经完成它的执行你明确检查:“如果(!myProcess.HasExited)“和”while(!myProcess.WaitForExit(1000));“ –
不按预期工作的原因是因为你进入循环,启动程序并等待程序结束后再开始下一个循环。您应该将循环中的进程监视移到另一个Thread上,以便所有程序都可以立即启动。 – Nunners