0

我的代码如下所示:

 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 等待,它只是继续移动到下一行。

我究竟做错了什么?谢谢。

4

1 回答 1

3

有两种方法可以等待进程退出。一个是同步的,另一个是异步的。

如果您更喜欢同步使用Process.WaitForExit否则使用Process.Exited事件。

所以在你打电话后,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
    }
}
于 2015-01-21T08:56:44.793 回答