我的代码如下:
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}
}然后:
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();我的问题如下:
在一个方法中有`wait_till_finish.WaitOne()‘,在我调用Qar_Function方法后,它处于等待状态,所以首先我想调用该方法,然后我想等到该方法执行完毕,然后,在qar_function方法中,我设置了AutoReset。
它不起作用。
我正在使用调试器,它不是在WaitOne等待,而是一直移到下一行。
我做错了什么?谢谢。
发布于 2015-01-21 16:56:45
有两种方法可以等待进程退出。一个是同步的,另一个是异步的。
如果您喜欢同步,请使用Process.WaitForExit,否则请使用Process.Exited event。
因此,在调用process.Start之后,您可以调用process.WaitForExit来等待它完成。
对我来说,看起来您只是在创建新线程,启动进程并计划等待它--同时另一个线程正在等待这个线程。所有这些看起来都是对资源的低效利用。您可以避免创建新线程,只需内联进程创建并在调用线程本身中等待它。在这种情况下,您甚至不需要AutoResetEvent。
在这一点上,你的代码变成:
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
}
}https://stackoverflow.com/questions/28062768
复制相似问题