【发布时间】:2023-04-10 14:26:04
【问题描述】:
这是我用来启动子进程并监控其输出的 C# 代码:
using (process = new Process()) {
process.StartInfo.FileName = executable;
process.StartInfo.Arguments = args;
process.StartInfo.UseShellExecute = false;
process.StartInfo.RedirectStandardOutput = true;
process.StartInfo.RedirectStandardInput = true;
process.StartInfo.CreateNoWindow = true;
process.Start();
using (StreamReader sr = process.StandardOutput) {
string line = null;
while ((line = sr.ReadLine()) != null) {
processOutput(line);
}
}
if (process.ExitCode == 0) {
jobStatus.State = ActionState.CompletedNormally;
jobStatus.Progress = 100;
} else {
jobStatus.State = ActionState.CompletedAbnormally;
}
OnStatusUpdated(jobStatus);
}
我在单独的 ThreadPool 线程中启动多个子进程(但在四核机器上一次不超过四个)。这一切都很好。
我遇到的问题是我的一个子进程将退出,但对sr.ReadLine() 的相应调用将阻塞,直到我的另一个子进程退出。我不确定它会返回什么,但除非我缺少某些东西,否则这不应该发生。
我的子进程没有任何东西会导致它们以任何方式“链接”——它们不会相互通信。发生这种情况时,我什至可以查看任务管理器/进程资源管理器,看到我的子进程实际上已退出,但在其标准输出上对 ReadLine() 的调用仍处于阻塞状态!
我已经能够通过将输出监视代码转出到一个新线程并执行process.WaitForExit() 来解决它,但这似乎是非常奇怪的行为。有人知道这里发生了什么吗?
【问题讨论】:
标签: c# pipe subprocess