Process.OutputDataReceived 是在哪个线程上引发和处理的?
我有一个多线程 winforms 应用程序。一个线程用于 GUI,一个线程用于后台处理。在后台处理中,我通过 Process 类与外部进程通信以发送接收数据。
我对我注册的 Process.OutputDataReceived 处理程序在哪个线程上运行感到困惑。根据 MS 文档:“OutputDataReceived 事件表明关联的进程已写入其重定向的 StandardOutput 流。”但尚不清楚是谁发起了这一事件。
请参见下面的示例代码:
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();
那么在这种情况下,DataReceivedFromProc 在哪个线程上运行?如果上面的代码在我的 GUI 线程和工作线程上执行,会有什么不同吗?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您应该设置
myProc.SynchronizingObject
属性 添加到您的窗体或控件。否则,我相信该事件将在 IO 完成线程(来自线程池)上引发。
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: