将 StdOut StreamReader 解析为 JSON

问题描述 投票:0回答:0

我正在使用

Process
类来对交互式应用程序进行 shell。我正在为标准输入编写一条指令,结果将是一个 JSON 跨多行发送到标准输出。

我正在为

EndOfStream
而苦苦挣扎
Process.StandardOutput

此代码有效:

using System.Text.Json;

Process proc = new Process();

proc.StartInfo.FileName = "xxx.exe"
proc.StartInfo.RedirectStandardInput = true;
proc.StartInfo.RedirectStandardOutput = true;
proc.StartInfo.UseShellExecute = false;

proc.Start();

//Send a command into Standard Input
// ... Code omitted

//Process response
var stdOut = proc.StandardOutput;
string result = "";
while (stdOut.Peek()>0)
{
    result += stdOut.ReadLine();
}

//Create the JSON
var doc = JsonDocument.Parse(result);

但是好像有点低效。

JsonDocument.Parse()
将接受一个
Stream
,所以也许我天真地希望我可以将标准输出流传递到
Parse
函数中,如下所示:

var doc = JsonDocument.Parse(stdOut.BaseStream);

但这只会无限期地阻塞。当我尝试时,也会发生同样的情况(我预计两者是相关的):

string result=""
while( ! stdOut.EndOfStream)
{
    result+=stdOut.ReadLine();
}

从周围阅读,似乎对于某些 StreamReader,即使流上没有任何可用内容,也未设置流结束标志。这很公平:以后可能会有更多。 但是有没有一种方法可以将这个流传递给 JSON 解析器而不阻塞它?

我想知道是否有一种方法是从 StreamReader 继承,并覆盖

EndOfStream
属性以使用
Peek()
方法代替?

顺便说一句,交互式应用程序非常慢,所以我希望我的 JSON 解析器在生成时开始解析(通常是大的)输出,从而抢先一步。因此,等到我拥有所有返回的行才开始解析会减慢速度。

c# json stream
© www.soinside.com 2019 - 2024. All rights reserved.