如何中断 IO 绑定线程

发布于 2024-09-30 04:51:59 字数 272 浏览 2 评论 0原文

我正在打开一个 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

一绘本一梦想 2024-10-07 04:51:59

我会冒险中止

try 
{ 
    Timer watchdog = new Timer(abortMe, Thread.CurrentThread, timeout, Timeout.Infinite);
    output = outputStream.ReadToEnd(); 
    watchdog.Dispose();
} 
catch (ThreadAbortException e) 
{ 
    return; 
} 

private void abortMe(object state)
{
    ((Thread)state).Abort()
}

实际上,当我使用 TCP 和 UDP 套接字时,我成功地关闭了流:它触发了 SocketException 并且线程被成功中断。

顺便问一下,您的流应该是输入流吗?你不应该读取输出流......

I would hazard aborting

try 
{ 
    Timer watchdog = new Timer(abortMe, Thread.CurrentThread, timeout, Timeout.Infinite);
    output = outputStream.ReadToEnd(); 
    watchdog.Dispose();
} 
catch (ThreadAbortException e) 
{ 
    return; 
} 

private void abortMe(object state)
{
    ((Thread)state).Abort()
}

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...

临风闻羌笛 2024-10-07 04:51:59

您可以尝试在 Process 对象以及流上调用 Dispose()。我想 outputStream 通过 Process.StandardOutput 链接到 Process 实例,因此这应该具有预期的效果。

编辑 - 请参阅我对 这个问题的回答 - .Net I/O 的这个区域容易出现死锁,如果可以选择的话,更喜欢异步 I/O。

You could try calling Dispose() on the Process object as well as on the stream. I imagine outputStream is linked to the Process instance via Process.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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文