我正在執行一些命令,我正在使用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