Reputation: 1252
I have the following code:
foreach(string fileName in chunkFiles)
{
p = GenerateProcessInstance();
p.StartInfo.Arguments = string.Format("{0} {1} false {2}", fileName, Id, logName);
p.Start();
p.WaitForExit();
sent += p.ExitCode;
}
What I want to do is if I have at least 2 chunks to run the EXE with 2 instances. My only problem is that I have WaitForExit
. I am using this because I need a parameter returned from the EXE.
How to solve this problem?
Upvotes: 1
Views: 3206
Reputation: 1252
At the end, the method used was:
Parallel.ForEach(
chunkFiles,
new ParallelOptions { MaxDegreeOfParallelism = 2 },
chunk =>
{
//create new paralel process - count limited to MaxDegreeOfParallelism
Process p = ProcessManager.GenerateProcessInstance();
p.StartInfo.Arguments = string.Format("{0} {1} {2} {3}", chunk, Id, logFileName, infoFileName);
p.Start();
p.WaitForExit();
sentEmails += p.ExitCode;
}
);
Upvotes: 0
Reputation: 582
Add a handler for Exited to handle the return value, like so
foreach(string fileName in chunkFiles)
{
p = GenerateProcessInstance();
p.StartInfo.Arguments = string.Format("{0} {1} false {2}", fileName, Id, logName);
p.Exited += new EventHandler(p_Exited);
p.Start();
}
protected void p_Exited(object sender, EventArgs e)
{
var p = (Process)sender;
// Handle p.ExitCode
}
Upvotes: 1
Reputation: 376
What I found out is that at least sometimes when you start two instances of an application, or start an instance of an application when one is already running, WaitForExit and Exited event don't work. If you look closely enough you'll see that the whole Process object goes haywire (and becomes useless) when you try to have multiple instances of the same application. I had to design a workaround that didn't rely on Process object.
Upvotes: 0
Reputation: 203823
Just start all of the process in a loop and then wait on all of them in another loop:
var processes = new List<Process>();
int sent = 0;
foreach (string fileName in chunkFiles)
{
Process p = GenerateProcessInstance();
p.StartInfo.Arguments = string.Format("{0} {1} false {2}", fileName, Id, logName);
p.Start();
processes.Add(p);
}
foreach (Process p in processes)
{
p.WaitForExit();
sent += p.ExitCode;
}
Upvotes: 1
Reputation: 31221
static void Main()
{
Thread t = new Thread(new ThreadStart(RunExe))
t.Start
Thread t2 = new Thread(new ThreadStart(RunExe))
t2.Start
}
public void RunExe()
{
foreach(string fileName in chunkFiles)
{
p = GenerateProcessInstance();
p.StartInfo.Arguments = string.Format("{0} {1} false {2}", fileName, Id, logName);
p.Start();
p.WaitForExit();
sent += p.ExitCode;
}
}
Upvotes: 0