C# - 如何在进程退出时关闭标准输入和输出流?
我有一个进程需要启动子进程并通过标准输入和输出与其进行通信。子进程应该能够自动终止;但是,我无法正确关闭流。
这是子进程/“客户端”进程的相关代码:
// This is started in a separate thread
private void watchStandardInput() {
string line = null;
do {
try {
line = Console.ReadLine();
} catch (IOException) {
return;
}
lock (inputWatcher) {
switch (line) {
// process command
}
}
} while (line != null);
}
// This is called from the main thread
private void updateStatus(string statusMessage) {
lock (inputWatcher) {
Console.WriteLine(statusMessage);
}
}
这是“服务器”代码:
// This is in the main thread
using (StreamReader sr = process.StandardOutput) {
while (!process.HasExited) {
processOutput(sr.ReadLine());
}
}
// Finally, commands are sent in a separate thread.
现在解决我遇到的问题:当子进程应该退出时,服务器停留在 sr.ReadLine () 并且客户端停留在 Console.ReadLine()
处。我做错了什么?
I have a process that needs to launch a child process and communicate with it through standard input and output. The child process should be able to automatically terminate itself; however, I am having trouble closing the streams properly.
Here is the relevant code from the child / "client" process:
// This is started in a separate thread
private void watchStandardInput() {
string line = null;
do {
try {
line = Console.ReadLine();
} catch (IOException) {
return;
}
lock (inputWatcher) {
switch (line) {
// process command
}
}
} while (line != null);
}
// This is called from the main thread
private void updateStatus(string statusMessage) {
lock (inputWatcher) {
Console.WriteLine(statusMessage);
}
}
And here's the "server" code:
// This is in the main thread
using (StreamReader sr = process.StandardOutput) {
while (!process.HasExited) {
processOutput(sr.ReadLine());
}
}
// Finally, commands are sent in a separate thread.
Now for the problem I am having: When the child process is supposed to be exiting, the server stays at sr.ReadLine()
and the client stays at Console.ReadLine()
. What am I doing wrong?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
确保执行 ReadLine() 的客户端线程将 IsBackground 设置为 true。不要在此线程上执行 Abort() / Join()。只需关闭所有非后台线程即可。我发现即使 IsBackground 设置为 true,在后台线程上执行 Abort() / Join() 也会导致我的测试应用程序等待输入,但是,删除 Abort() / Join() 并定期退出效果很好。
Make sure the client thread doing the ReadLine() has IsBackground set to true. Do NOT do an Abort() / Join() on this thread. Just close down all non-background threads. I found that even with IsBackground set to true, doing an Abort() / Join() on the background thread caused my test app to wait for input, however, removing the Abort() / Join() and just exiting regularly worked fine.