C#'System.InvalidOperationException'不能在过程流混合同步和异步操作

问题描述:

我想从一个CMD过程反复读,反复打印输出为好,但我使用whil​​e循环是一个Task.Run里面,以便它不锁程序,但有一些问题,异步与非异步方法,我不太明白。我得到我需要没有在Task.Run的pProcess.StandardOutput.ReadToEnd,但我怎么会在我的code实现这个?谢谢!

I am trying to read from a CMD process repeatedly, and print out the output repeatedly as well, But the while loop I am using is inside a Task.Run so that it doesn't lock the program up, but there is some problem with ASync and non-ASync methods that I don't quite understand. I get that I need to not have the pProcess.StandardOutput.ReadToEnd in a Task.Run, but how would I implement this in my code? Thanks!

Task.Run(() => 
    {
        while (true)
        {
            string output = pProcess.StandardOutput.ReadToEnd();
            System.Console.Write(output);
        }
     });

在这里输入的形象描述

有同在一个单独的任务与 Task.Run 执行此code,我认为没有问题您在code在什么地方正在调用像BeginErrorReadLine或BeginOutputReadLine一些异步方法。这SO的回答可以帮助:我想读在C#过程的输出,但我得到这个消息"不能混用同步和异步在工艺流运QUOT;。

There's no problem with executing this code in a seperate Task with Task.Run I think you're calling some asynchronous method like BeginErrorReadLine or BeginOutputReadLine somewhere before in your code. This SO answer may help: I am trying to read the output of a process in c# but I get this message "Cannot mix synchronous and asynchronous operation on process stream."