C#我需要在单独的线程上读取标准输出吗?
在C#中,我试图运行一个命令行程序,从stdin获取输入,然后将输出返回给stdout。我需要保持cmd.exe运行(使用/k)并在for循环中发送文本,然后在发送下一个文本之前等待输出。如果不重定向stdout,但在重定向stdout之后,它就不起作用了。最初,我从stdout(虽然要晚很多)获得了数据,现在除了启动程序的初始调用之外,它不再工作了。这表示“或者,您可以通过创建两个线程并在单独的线程上读取每个流的输出来避免死锁情况。” 这会解决我的问题吗?如果会,我会怎么做 代码设置如下:C#我需要在单独的线程上读取标准输出吗?,c#,redirect,process,stdout,stdin,C#,Redirect,Process,Stdout,Stdin,在C#中,我试图运行一个命令行程序,从stdin获取输入,然后将输出返回给stdout。我需要保持cmd.exe运行(使用/k)并在for循环中发送文本,然后在发送下一个文本之前等待输出。如果不重定向stdout,但在重定向stdout之后,它就不起作用了。最初,我从stdout(虽然要晚很多)获得了数据,现在除了启动程序的初始调用之外,它不再工作了。这表示“或者,您可以通过创建两个线程并在单独的线程上读取每个流的输出来避免死锁情况。” 这会解决我的问题吗?如果会,我会怎么做 代码设置如下: S
StringBuilde sb = new StringBuilder();
Process process = new Process();
process.StartInfo.RedirectStandardError = true;
process.StartInfo.WorkingDirectory = workingdirectory;
process.StartInfo.UseShellExecute = false;
process.StartInfo.FileName = "cmd.exe";
process.StartInfo.Arguments = "/k";
process.StartInfo.RedirectStandardOutput = true;
process.StartInfo.RedirectStandardInput = true;
process.EnableRaisingEvents = true;
process.OutputDataReceived += (sender, args) => AppendData(args.Data); //this appends the output to a stringbuilder
process.ErrorDataReceived += (sender, args) => AppendError(args.Data);
process.Start();
//sw is a streamwriter
sw= process.StandardInput;
//now call the command line code
sw.WriteLine(" some.exe some.arg ");
process.BeginOutputReadLine();
foreach(DataRow row in dtMydata.Rows)
{
mytext=row["Text"].toString();
sw.WriteLine(mytext);
sw.WriteLine(Environment.NewLine); //This redirects the text to the program,
}
我记得,如果您想重定向STDIN和STDOUT,您需要异步地这样做。我想有一个.NET的例子在。嗨,谢谢你的输入。我还添加了process.BeginErrorReadLine()以对错误流进行异步读取,并且在程序开始运行后仍然无法获取标准输出流。我有一个同步调用来获取stdin,在stdout和stderr上有一个异步调用。我想我需要探索如何在单独的线程中运行这些。这在您提供的链接和我上面引用的链接上都有建议。仔细看,在调试中,“不能在进程流上混合同步和异步操作”。只要我执行异步调用进程,BeginOutputReadLine()。需要进一步调查我要放弃这个。。。使用我的代码和许多示例程序,当我在启动后立即调用异步方法process.BeginOutputReadLine()时,我得到一个错误“无法在进程流上混合同步和异步操作”