I am trying to execute some commands in my program, for that I am using System.Diagnostics.Process. I managed to set it working, when I execute the commands 1 by 1 the returns are correct. I then tried to speed up the process by creating tasks for each process execution, and here is where I am having problems.
Here is the class to execute the commands:
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;
}
}
And this is my Main:
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();
}
}
This is my output:
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
Now, I think that my problem is related with the OutputDataReceived event being in a diferent thread, but I am not fully sure. Anyone knows what is the problem and how can I solve it?