Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 203
Josh Avatar asked Apr 12 '11 22:04

Josh


2 Answers

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).

like image 192
SLaks Avatar answered Sep 20 '22 08:09

SLaks


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.

like image 43
Josh Avatar answered Sep 20 '22 08:09

Josh