3

I have a thread that is blocking on a Networkstream Read call. How do I best abort this thread? I tried calling Thread.Abort on the thread from another thread, which according to MSDN should raise a ThreadAbortException. However the ThreadAbortException is not raised at all in the thread. It is however, when I remove the blocking Read call and just have the thread sit in a loop. What is the best way to do this? Can I wait on the Read call and an event at the same time so the thread unblocks if either occurs? Then I could just signal that event from another thread.

4

3 回答 3

3

关闭插座!然后 Read 应该抛出一个异常。

于 2012-08-04T11:36:51.093 回答
2

Thread.Abort仅在线程运行托管代码时中止,但您的线程正在等待非托管套接字,因此在套接字解除阻塞之前不会发生任何事情。

关闭套接字是这里的最佳选择。

于 2012-08-04T12:32:09.950 回答
1

stream.ReadTimeout = timeout; 
// timeout in ms

使用前

stream.Read(....

这将强制读取超时,并允许在指定超时(以毫秒为单位)没有读取任何内容时执行某些操作。请参阅Stream::ReadTimeout 属性或MSDN 上的这篇文章。这样,您可以实现仅在指定timeout阻塞的读取。使用其他同步方法来确定是应该继续读取还是应该完成线程。超时会抛出异常。

于 2012-08-04T16:19:00.597 回答