如何停止 NetworkStream 上的阻塞 StreamReader.EndOfStream

发布于 2024-10-31 06:08:10 字数 948 浏览 10 评论 0原文

我有一个使用 TcpClient 的类,该类在 NetworkStream 上旋转 Thread 执行 while (!streamReader.EndOfStream) {}代码>.只要TCP连接打开并且没有可用的数据可读取,EndOfStream就会阻塞执行,所以我想知道我应该做什么来中止从线程外部的读取。

由于 EndOfStream 是阻塞的,因此将名为 stop 的私有字段设置为 true 单独不会有多大作用(至少在我的测试中) ,所以我所做的如下:

// Inside the reading thread:

try
{
    StreamReader streamReader = new StreamReader(this.stream);

    while (!streamReader.EndOfStream)
    {
        // Read from the stream
    }
}
catch (IOException)
{
    // If it isn't us causing the IOException, rethrow
    if (!this.stop)
        throw;
}

// Outside the thread:

public void Dispose()
{
    // Stop. Hammer Time!
    this.stop = true;

    // Dispose the stream so the StreamReader is aborted by an IOException.
    this.stream.Dispose();
}

这是中止从 NetworkStream 读取的推荐方法,还是有其他一些我可以用来安全(但强制)处置所有内容的技术?

I have rather class using TcpClient that spins of a Thread doing while (!streamReader.EndOfStream) {} on the NetworkStream. As long as the TCP connection is open and there is no available data to read, EndOfStream will block execution, so I wonder what I should do to abort the reading from outside the thread.

Since EndOfStream is blocking, setting a private field called stop to true won't do much good alone (at least in my testing of it), so what I've done is the following:

// Inside the reading thread:

try
{
    StreamReader streamReader = new StreamReader(this.stream);

    while (!streamReader.EndOfStream)
    {
        // Read from the stream
    }
}
catch (IOException)
{
    // If it isn't us causing the IOException, rethrow
    if (!this.stop)
        throw;
}

// Outside the thread:

public void Dispose()
{
    // Stop. Hammer Time!
    this.stop = true;

    // Dispose the stream so the StreamReader is aborted by an IOException.
    this.stream.Dispose();
}

Is this the recommended way to abort reading from a NetworkStream or is there some other technique I can use to safely (but forcibly) dispose everything?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(1

傲鸠 2024-11-07 06:08:10

您应该中止线程。由于您已经使用了 try/catch,因此中止线程(导致异常)将被优雅地捕获,并且您可以处理诸如关闭流和其他内容之类的情况。

中止线程(许多人认为这是永远不要做的事情)的主要问题是当我们中止线程时线程在哪里以及后果是什么。如果我们可以处理它,中止线程就可以了。

You should abort the thread. Since you already use a try/catch, aborting the thread (causes an exception) would be gracefully caught and you can handle the situation like closing the stream and other stuff.

The main thing about aborting a thread (many think about it as a never to do thing), is where is the thread when we abort it and what are the consequences. If we can handle it, it's OK to abort a thread.

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