C#过程。无阻塞的标准错误读取

C#过程。无阻塞的标准错误读取,c#,process,C#,Process,我是一名编程老师,我正在为学生的硬件开发一个自动检查器(都是控制台应用程序)。基本上,我使用一些Process.Start()(带有一些输入文件)运行学生代码,并检查其输出是否如预期的那样。 如果由于某种原因,学生代码没有成功完成,我会使用进程标准错误重定向发送他们代码引发的异常 然而,我想做得更好。我想找到写入进程标准输入的输入行,在该输入行发生异常之后。我该怎么做?我的当前代码大致如下: ProcessStartInfo psi = new ProcessStartInfo(students

我是一名编程老师,我正在为学生的硬件开发一个自动检查器(都是控制台应用程序)。基本上,我使用一些Process.Start()(带有一些输入文件)运行学生代码,并检查其输出是否如预期的那样。 如果由于某种原因,学生代码没有成功完成,我会使用进程标准错误重定向发送他们代码引发的异常

然而,我想做得更好。我想找到写入进程标准输入的输入行,在该输入行发生异常之后。我该怎么做?我的当前代码大致如下:

ProcessStartInfo psi = new ProcessStartInfo(students_exe_path);
psi.UseShellExecute = false;
psi.RedirectStandardInput = true;
psi.RedirectStandardOutput = true;
psi.RedirectStandardError = true;

String randomInputFile = randomInputFilesFolder + "\\" + "test.txt";
psi.WorkingDirectory = randomInputFilesFolder;
Process p = Process.Start(psi);
StreamWriter inputWriter = p.StandardInput;
String[] inputLines = File.ReadAllLines(randomInputFile);
foreach (String line in inputLines)
{
    // here I wanted to read the standart error so far (before writing next input line)
    String errorTextBefore = p.StandardError.ReadToEnd(); // can not use this because blocks progress.

    inputWriter.WriteLine(line); // sending next input line to students app

    // here I wanted to read the standart error so far (after writing next input line)
    String errorTextAfter = p.StandardError.ReadToEnd(); // can not use because blocks
    if (errorTextBefore != errorTextAfter) Console.WriteLine("Line {0} caused the exception",line);
}
或者我可以从p.StandartInput检查流程中没有“消耗”哪些文本


Tamir

您只能从一个流中读取同步数据。要从错误流和标准流中读取,您需要读取异步并订阅事件。请参阅:或者您只能从一个流中读取同步数据。要从错误流和标准流中读取,您需要读取异步并订阅事件。见:或