2010-04-21 9 views
2

我想这C#进程<instance> .StandardOutput InvalidOperationException“无法在进程流上混合同步和异步操作。”

 myProcess = new Process(); 

     myProcess.StartInfo.CreateNoWindow = true; 
     myProcess.StartInfo.WindowStyle = ProcessWindowStyle.Hidden; 

     myProcess.StartInfo.FileName = "Hello.exe"; 

     myProcess.StartInfo.Arguments ="-say Hello"; 
     myProcess.StartInfo.UseShellExecute = false; 

     myProcess.OutputDataReceived += new DataReceivedEventHandler(myProcess_OutputDataReceived); 
     myProcess.ErrorDataReceived += new DataReceivedEventHandler(myProcess_OutputDataReceived); 
     myProcess.Exited += new EventHandler(myProcess_Exited); 
     myProcess.EnableRaisingEvents = true; 

     myProcess.StartInfo.RedirectStandardOutput = true; 
     myProcess.StartInfo.RedirectStandardError = true; 
     myProcess.StartInfo.ErrorDialog = true; 
     myProcess.StartInfo.WorkingDirectory = "D:\\Program Files\\Hello"; 

     myProcess.Start(); 

     myProcess.BeginOutputReadLine(); 
     myProcess.BeginErrorReadLine(); 

然后我得到这个错误.. alt text http://img188.imageshack.us/img188/3759/errorstack.jpg

我的过程需要很长时间才能完成,所以我需要显示在运行时进度。

回答

3

您不需要拨打ReadLine(),读取的文本行就是在​​对象中传递给您的属性之一。

+0

我试过,但仍然是相同的: 空隙myProcess_OutputDataReceived(对象发件人,DataReceivedEventArgs E) { 的StreamReader myStreamReader = myProcess.StandardOutput; String str = myStreamReader.ReadLine(); textBox_StdOutPut.Text + = str; } – Rick2047 2010-04-21 09:11:22

+2

@ Rahul2047:对不起,但通过您在之前的评论中输入的代码,它看起来并不像codeka建议的那样。您可以通过使用DataReceivedEventArgs.Data属性的值访问流程发出的当前行:myProcess_OutputDataReceived(object sender,DataReceivedEventArgs e){textBox_StdOutPut.Text + = e.Data + Environment.NewLine; } – 2010-04-21 09:41:55

+0

非常感谢。现在它可以工作。谢谢。 – Rick2047 2010-04-21 10:45:05