我正在使用C#,并且无法理解如何从子进程异步读取stdout.我想要做的是创建一个子进程来执行一个应用程序,然后在文本框中显示从该进程'stdout收到的任何内容.我需要立即查看子进程中的每个输出字符,并且不能等待一行完成,因此我认为该Process.OutputDataReceived事件不符合我的目的.你能告诉我一个理智的方法吗?
我已经尝试调用Process.StandardOutput.BaseStream.BeginRead()并向其传递回调函数,但在此回调函数中,我收到了一个异常Process.StandardOutput.BaseStream.EndRead().
我的代码看起来像这样(子进程是一个脚本引擎 - 缩写为"SE" - 用于验证外部设备的功能.脚本按顺序执行,每个脚本需要一个SE应用程序实例)
private bool startScript()
{
// Starts the currently indexed script
if (null != scriptList)
{
if (0 == scriptList.Count || scriptListIndexer == scriptList.Count)
{
// If indexer equals list count then there are no active scripts in
// the list or the last active script in the list has just finished
return false; // ## RETURN ##
}
if (ScriptExecutionState.RUNNING == scriptList[scriptListIndexer].executionState)
{
return false; …Run Code Online (Sandbox Code Playgroud) 我很难解读有关Process.StandardOutpout的MSDN文档,以了解Read(Char [],Int32,Int32)方法是否阻塞.我的理解是它不应该阻塞,但是当我将RedirectStandardInput设置为true时它似乎就是这样.
有没有人有这方面的经验; 或者对我遇到的问题有一些解释?
这里的上下文是我不想等待整行(即使用行终止符),或者在读取标准输出之前退出进程.另外我不想使用回调.我想在进程写入时同步读取StdOut.
这是我的代码的简化版本:
string command = @"C:\flex_sdks\flex_sdk_4.5.1.21328\bin\fcsh.exe";
Process p = new Process();
p.StartInfo.UseShellExecute = false;
p.StartInfo.RedirectStandardInput = false; # <-- if I set this to true, then
# the program hangs on
# p.StandardOutput.Read later on
p.StartInfo.RedirectStandardOutput = true;
p.StartInfo.CreateNoWindow = true;
p.StartInfo.FileName = command;
p.Start();
StringBuilder sb_stdout = new StringBuilder(1024);
char[] buffer = new char[64];
int nb_bytes_read;
while (true) {
do {
nb_bytes_read = p.StandardOutput.Read(buffer, 0, buffer.Length);
sb_stdout.Append(new string(buffer, 0, nb_bytes_read));
} while …Run Code Online (Sandbox Code Playgroud)