我要使用C#进行的操作是:
我正在使用while循环检查子流程的执行时间,但是当我尝试从Process.StandardOutput获取输出数据时,该线程将被阻塞,并且直到子流程结束时,超时检查循环才起作用
是否有任何方法可以在StreamReader上进行非阻塞读取,或者在不使用非阻塞读取的情况下具有相同效果的解决方法?
答案 0 :(得分:0)
您是否使用Process类启动C ++程序?
如果是这样,您可以read asynchronously the output进行事件。
来自msdn的示例:
private static int lineCount = 0;
private static StringBuilder output = new StringBuilder();
public static void Main()
{
Process process = new Process();
process.StartInfo.FileName = "ipconfig.exe";
process.StartInfo.UseShellExecute = false;
process.StartInfo.RedirectStandardOutput = true;
process.OutputDataReceived += new DataReceivedEventHandler((sender, e) =>
{
// Prepend line numbers to each line of the output.
if (!String.IsNullOrEmpty(e.Data))
{
lineCount++;
output.Append("\n[" + lineCount + "]: " + e.Data);
}
});
process.Start();
// Asynchronously read the standard output of the spawned process.
// This raises OutputDataReceived events for each line of output.
process.BeginOutputReadLine();
process.WaitForExit();
// Write the redirected output to this application's window.
Console.WriteLine(output);
process.WaitForExit();
process.Close();
Console.WriteLine("\n\nPress any key to exit.");
Console.ReadLine();
}