Reputation: 461
My code is as shown below:
static AutoResetEvent wait_till_finish = new AutoResetEvent(false);
...if (File.Exists("try.exe"))
{
Thread quartus_thread = new Thread(() => qar_function(@"\quartus");
quartus_thread.Start();
wait_till_finish.WaitOne();
// ONLY after command mode action was finished, and AutoResetEvent is set, lookfor some file in folder
if (File.Exists("def")) {//do something}
}
And later on:
public void qar_function(string abc)
{ //does something...
ProcessStartInfo procStartInfo = new ProcessStartInfo("cmd", "/k " + String.Join(" ", args));
procStartInfo.RedirectStandardOutput = true;
procStartInfo.RedirectStandardError = true;
procStartInfo.UseShellExecute = false;
procStartInfo.CreateNoWindow = false;
Process proc = new Process();
proc.StartInfo = procStartInfo;
proc.Start();
// ***** now set AutoResetEvent:
wait_till_finish.set();
My problem is as follows:
I have `wait_till_finish.WaitOne()' in one method, and it's in wait state AFTER I'm calling the Qar_Function method, so first I want to call the method, then I want to wait till the method is executed and finished, and then, inside the qar_function method, I set the AutoReset.
It is not working.
I'm using the debugger, and it is not waiting at the WaitOne, it's just keep moving to the next line.
What am I doing wrong? Thx.
Upvotes: 0
Views: 1546
Reputation: 73482
There are two ways to wait for the process exit. One is synchronous and another is asynchronous.
If you prefer synchronous use Process.WaitForExit otherwise use Process.Exited event.
So after you call process.Start
you can call process.WaitForExit
to wait for it to complete.
Also for me it looks like you're simply creating new thread and starting the process and planning to wait for it -- at the same time another thread is waiting for this thread. All this looks inefficient use of resources. You can avoid creating new thread and just inline the process creation and waiting for it in the calling thread itself. In that case you don't even need AutoResetEvent
.
At that point your code becomes:
if (File.Exists("try.exe"))
{
ProcessStartInfo procStartInfo = new ProcessStartInfo("cmd", "/k " + String.Join(" ", args));
procStartInfo.RedirectStandardOutput = true;
procStartInfo.RedirectStandardError = true;
procStartInfo.UseShellExecute = false;
procStartInfo.CreateNoWindow = false;
Process proc = new Process();
proc.StartInfo = procStartInfo;
proc.Start();
proc.WaitForExit();
//At this point the process you started is done.
if (File.Exists("def"))
{
//do something
}
}
Upvotes: 3