1

我比较TcpClient喜欢Threadwhile (!streamReader.EndOfStream) {}. NetworkStream只要 TCP 连接打开并且没有可读取的数据,EndOfStream就会阻塞执行,所以我想知道我应该怎么做才能中止从线程外部读取。

由于EndOfStream是阻塞的,单独设置一个名为stopto的私有字段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();
}

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

4

1 回答 1

0

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.

于 2011-04-07T10:29:39.240 回答