简体   繁体   中英

What thread is Process.OutputDataReceived raised and handled on?

I have a multi-threaded winforms application. One thread for the GUI, and one thread for background processing. In the background processing, I communicate with an external process via the Process class to send an receive data.

I am confused about what thread the handler that I registered Process.OutputDataReceived is run on. According to MS documentation: "The OutputDataReceived event indicates that the associated Process has written to its redirected StandardOutput stream." But it isn't clear who is raising the event.

See example code below:

myProc= new Process();
myProc.StartInfo.UseShellExecute = false;
myProc.StartInfo.RedirectStandardOutput = true;
myProc.StartInfo.RedirectStandardError = true;
myProc.StartInfo.RedirectStandardInput = true;
myProc.StartInfo.FileName = "myapp.exe";
myProc.StartInfo.Arguments = arguments;
myProc.StartInfo.CreateNoWindow = true;
myProc.OutputDataReceived += new DataReceivedEventHandler(DataReceivedFromProc);
myProc.ErrorDataReceived += new DataReceivedEventHandler(ErrorReceivedFromProc);
myProc.Start();
myOutputStream = myProc.StandardInput;
myProc.BeginOutputReadLine();
myProc.BeginErrorReadLine();

So in this case, what thread is DataReceivedFromProc run on? Does it make a difference if the above is executed on my GUI thread vs worker thread?

You should set the myProc.SynchronizingObject property to your form or control.

Otherwise, I believe the event will be raised on an IO completion thread (from the ThreadPool).

Also see the user comment at the very bottom of this page :

Process.OutputDataReceived is raised on a different thread than the one that instantiated and configured a Process object, and started the process.

If the Process object is instantiated on the main (or UI) thread, you won't be able to update UI running on that thread from the OutputDataReceived event handler. Instead, you'll have to use delegates to send a message to the main thread for processing.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM