gpt4 book ai didi

c# - 外部进程在异步读取输出时阻塞主线程

转载 作者:太空宇宙 更新时间:2023-11-03 10:41:43 25 4
gpt4 key购买 nike

所以我的 WPF 应用程序中有以下代码

        ghci = new Process
{
StartInfo = new ProcessStartInfo("ghci")
{
WorkingDirectory = System.IO.Path.GetDirectoryName(path),
Arguments = System.IO.Path.GetFileName(path),
RedirectStandardOutput = true,
RedirectStandardInput = true,
UseShellExecute = false,
CreateNoWindow = true
}
};
ghci.OutputDataReceived += (obj, data) =>
{
this.Dispatcher.InvokeAsync(() =>
{
ghciOutput.AppendText(data.Data + "\n");
ghciOutput.Focus();
ghciOutput.CaretIndex = ghciOutput.Text.Length;
ghciOutput.ScrollToEnd();
ghciInput.Focus();
Keyboard.Focus(ghciInput);
});
};
ghci.Start();
ghci.BeginOutputReadLine();

但是当进程开始输出大量数据时,该输出中的每一行都会非常快速地触发事件,并且整个应用程序会卡住。为什么会这样?我想我已经确保它没有通过首先执行异步的 BeginOutputReadLine(尽管我很可能不知道这到底是什么意思)然后在事件内部执行 InvokeAsync 以确保主线程在它时更新输出有时间。

我还应该注意,当应用程序卡住时,输出文本框不会更新新数据,尽管这可能只是应用程序卡住的结果。

最佳答案

您需要在 tje OutputDataReceived 缓冲区中缓冲传入数据,并通过 InvokeAsync 以 block (每 2-3 秒)左右的方式将其分派(dispatch)到 UI案例比现在少。

您可以缓冲到 string 中,并且可以每 100 行左右发送一次(为了不测量时间)。不要忘记在分派(dispatch)后清除字符串,或者只使用另一个实例并收集旧实例。

此时您正在使用 UI 更新终止 UI 线程。

我认为这很清楚。如果您需要示例,请告诉我,我会尽力而为。

关于c# - 外部进程在异步读取输出时阻塞主线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25093733/

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