如何中断 IO 绑定线程
我正在打开一个 System.Diagnostic.Process 来从进程中读取标准输出,并且我希望能够在经过一定时间后中断它。
try
{
output = outputStream.ReadToEnd();
}
catch (ThreadInterruptedException e)
{
return;
}
这是行不通的,因为线程位于 ReadToEnd() 方法中。我尝试从主线程关闭流,希望能够使 Read 方法结束,但这也不起作用。
I am opening a System.Diagnostic.Process to read the stdout from a process and I would like to be able to interrupt it after a certain elapsed time.
try
{
output = outputStream.ReadToEnd();
}
catch (ThreadInterruptedException e)
{
return;
}
That doesn't work since the thread is in the ReadToEnd() method. I attempted to close the stream from the main thread, hoping that'd EOF the Read method, but that didn't work either.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我会冒险中止
实际上,当我使用 TCP 和 UDP 套接字时,我成功地关闭了流:它触发了 SocketException 并且线程被成功中断。
顺便问一下,您的流应该是输入流吗?你不应该读取输出流......
I would hazard aborting
Actually I succeed in closing the stream when I work with TCP and UDP sockets: it triggers a SocketException and the thread gets successfully interrupted.
By the way, should your stream be an input stream? You're not supposed to read an output stream...
您可以尝试在
Process
对象以及流上调用Dispose()
。我想outputStream
通过 Process.StandardOutput 链接到Process
实例,因此这应该具有预期的效果。编辑 - 请参阅我对 这个问题的回答 - .Net I/O 的这个区域容易出现死锁,如果可以选择的话,更喜欢异步 I/O。
You could try calling
Dispose()
on theProcess
object as well as on the stream. I imagineoutputStream
is linked to theProcess
instance viaProcess.StandardOutput
so this ought to have the desired effect.EDIT - see my answer to this question - this area of .Net I/O is prone to deadlocking, prefer async I/O if that is an option.