gpt4 book ai didi

c# - process.OutputDataReceived 未读取所有行

转载 作者:行者123 更新时间:2023-12-02 20:03:12 26 4
gpt4 key购买 nike

cmd 的结果

C:\Users\XXXXX>adb start-server
* daemon not running. starting it now *
* daemon started successfully *

C:\Users\XXXXX>

我的 C# 代码。

public string devicesPlus()
{
psi.Arguments = "start-server";
call = Process.Start(psi);
call.OutputDataReceived += new DataReceivedEventHandler(call_OutputDataReceived);
call.ErrorDataReceived += new DataReceivedEventHandler(call_OutputDataReceived);
call.EnableRaisingEvents = true;
call.Exited += new EventHandler(call_Exited);
call.Start();
call.BeginOutputReadLine();
call.BeginErrorReadLine();
call.StandardInput.Close();
call.WaitForExit();
return outData.ToString();
}

private void call_OutputDataReceived(object sender, DataReceivedEventArgs e)
{
if (e.Data != null)
{
outData.Append(e.Data);
}
}

现在,当我调用 devicesPlus 时,有时我只得到 * 守护进程未运行。现在就开始 *有时它只是在后台工作,没有结果..你们能告诉我我的代码有什么问题吗?为什么我没有像 cmd 那样得到正确的返回值。C# 新手,抱歉英语不好...

更新如果我从应用程序外部杀死 adb,我会突然收到软件的回复。

最佳答案

WaitForExit() 仅等待进程退出。它不会等待您的进程接收所有输出,因此您会遇到竞争条件。

call_OutputDataReceived 将使用 e.Data == null 进行调用,以表示输出结束。在使用 outData.ToString() 之前,您需要等待该调用。

例如,您可以使用 new CountdownEvent(2) 来等待两个流的结束:

    CountdownEvent countdownEvent;

public string devicesPlus()
{
psi.Arguments = "start-server";
countdownEvent = new CountdownEvent(2);
call = Process.Start(psi);
call.OutputDataReceived += new DataReceivedEventHandler(call_OutputDataReceived);
call.ErrorDataReceived += new DataReceivedEventHandler(call_OutputDataReceived);
call.EnableRaisingEvents = true;
call.Exited += new EventHandler(call_Exited);
call.Start();
call.BeginOutputReadLine();
call.BeginErrorReadLine();
call.StandardInput.Close();
call.WaitForExit();
countdownEvent.Wait();
return outData.ToString();
}

private void call_OutputDataReceived(object sender, DataReceivedEventArgs e)
{
if (e.Data != null)
{
// prevent race condition when data is received form stdout and stderr at the same time
lock (outData)
{
outData.Append(e.Data);
}
}
else
{
// end of stream
countdownEvent.Signal();
}
}

关于c# - process.OutputDataReceived 未读取所有行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16495677/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com