ProcessStartInfo hanging on “WaitForExit”? Why?

前端 未结 22 1897
佛祖请我去吃肉
佛祖请我去吃肉 2020-11-22 02:59

I have the following code:

info = new System.Diagnostics.ProcessStartInfo(\"TheProgram.exe\", String.Join(\" \", args));
info.CreateNoWindow = true;
info.Win         


        
22条回答
  •  灰色年华
    2020-11-22 03:02

    I tried to make a class that would solve your problem using asynchronous stream read, by taking in account Mark Byers, Rob, stevejay answers. Doing so I realised that there is a bug related to asynchronous process output stream read.

    I reported that bug at Microsoft: https://connect.microsoft.com/VisualStudio/feedback/details/3119134

    Summary:

    You can't do that:

    process.BeginOutputReadLine(); process.Start();

    You will receive System.InvalidOperationException : StandardOut has not been redirected or the process hasn't started yet.

    ============================================================================================================================

    Then you have to start asynchronous output read after the process is started:

    process.Start(); process.BeginOutputReadLine();

    Doing so, make a race condition because the output stream can receive data before you set it to asynchronous:

    process.Start(); 
    // Here the operating system could give the cpu to another thread.  
    // For example, the newly created thread (Process) and it could start writing to the output
    // immediately before next line would execute. 
    // That create a race condition.
    process.BeginOutputReadLine();
    

    ============================================================================================================================

    Then some people could say that you just have to read the stream before you set it to asynchronous. But the same problem occurs. There will be a race condition between the synchronous read and set the stream into asynchronous mode.

    ============================================================================================================================

    There is no way to acheive safe asynchronous read of an output stream of a process in the actual way "Process" and "ProcessStartInfo" has been designed.

    You are probably better using asynchronous read like suggested by other users for your case. But you should be aware that you could miss some information due to race condition.

提交回复
热议问题