C#'System.InvalidOperationException'不能在进程流上混合同步和异步操作 [英] C# 'System.InvalidOperationException' Cannot mix synchronous and asynchronous operation on process stream

查看:4394
本文介绍了C#'System.InvalidOperationException'不能在进程流上混合同步和异步操作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图从一个CMD进程重复读取,并打印输出重复以及,但我使用的while循环是在Task.Run内,以便它不锁定程序,但有一些问题与ASync和非ASync方法,我不太明白。我得到,我需要在一个Task.Run中没有pProcess.StandardOutput.ReadToEnd,但我如何在我的代码实现这一点?感谢!

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

c> c>我认为你正在调用一个单独的任务中执行这个代码没有问题。 Task.Run 一些异步方法像BeginErrorReadLine或BeginOutputReadLine之前的你的代码。这个SO回答可能有帮助:我试图读取在c#中的进程的输出,但我得到这个消息不能混合同步和异步对过程流进行操作。


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);
        }
     });

解决方案

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

这篇关于C#'System.InvalidOperationException'不能在进程流上混合同步和异步操作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆