我正在执行一些命令,我正在使用System.Diagnostics.Process
。我设法设置它的工作,当我一一执行命令时,返回是正确的。然后我试图通过为每个流程执行创建任务来加速流程,这里是我遇到问题的地方。在多任务环境中执行进程
这里是执行命令的类:
class ProcessExec
{
public string Start(string command)
{
string res = "";
Process process = new Process();
process.EnableRaisingEvents = true;
process.StartInfo.FileName = "powershell.exe";
process.StartInfo.Arguments = command;
process.StartInfo.UseShellExecute = false;
process.StartInfo.RedirectStandardOutput = true;
process.StartInfo.CreateNoWindow = true;
process.OutputDataReceived += (object sender, DataReceivedEventArgs e) =>
{
res = res + e.Data;
};
process.Start();
process.BeginOutputReadLine();
process.WaitForExit(10000);
return res;
}
}
,这是我公司主营:
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Start");
List<Task> tasks = new List<Task>();
ProcessExec exec = new ProcessExec();
Stopwatch sw = new Stopwatch();
sw.Start();
string res1 = "";
tasks.Add(Task.Run(() => { res1 = exec.Start("date"); }));
string res2 = "";
tasks.Add(Task.Run(() => { res2 = exec.Start("hostname"); }));
string res3 = "";
tasks.Add(Task.Run(() => { res3 = exec.Start("date"); }));
string res4 = "";
tasks.Add(Task.Run(() => { res4 = exec.Start("date"); }));
string res5 = "";
tasks.Add(Task.Run(() => { res5 = exec.Start("date"); }));
string res6 = "";
tasks.Add(Task.Run(() => { res6 = exec.Start("ipconfig"); }));
string res7 = "";
tasks.Add(Task.Run(() => { res7 = exec.Start("date"); }));
string res8 = "";
tasks.Add(Task.Run(() => { res8 = exec.Start("date"); }));
Task.WaitAll(tasks.ToArray());
sw.Stop();
Console.WriteLine(sw.Elapsed.TotalSeconds);
Console.WriteLine("1 - " + res1);
Console.WriteLine("2 - " + res2);
Console.WriteLine("3 - " + res3);
Console.WriteLine("4 - " + res4);
Console.WriteLine("5 - " + res5);
Console.WriteLine("6 - " + res6);
Console.WriteLine("7 - " + res7);
Console.WriteLine("8 - " + res8);
Console.WriteLine("End");
Console.ReadKey();
}
}
这是我的输出:
Start
7,4867498
1 - 22 de julho de 2017 10:25:46
2 -
3 - 22 de julho de 2017 10:25:48
4 - 22 de julho de 2017 10:25:48
5 -
6 -
7 - 22 de julho de 2017 10:25:48
8 - 22 de julho de 2017 10:25:48
End
现在,我认为,我的问题与OutputDataReceived事件处于不同的线程有关,但我不完全确定。任何人都知道什么是问题,我该如何解决它?
您的'开始'方法不会等待进程的执行。我的意思是你使用'process.WaitForExit(10000);'与asynchronus事件处理程序,但你的过程仍然在执行,当你返回结果。所以只需使用'process.WaitForExit()'。有关详细信息,您可以看到[MSDN上的注释](https://msdn.microsoft.com/en-us/library/ty0d8k56(v = vs.110).aspx#Anchor_2) –
哦,是的,我也读了关于WaitForExit(Int32)的MSDN文档,我认为它做了别的。感谢您的帮助。 – lulas