我比较TcpClient
喜欢Thread
在while (!streamReader.EndOfStream) {}
. NetworkStream
只要 TCP 连接打开并且没有可读取的数据,EndOfStream
就会阻塞执行,所以我想知道我应该怎么做才能中止从线程外部读取。
由于EndOfStream
是阻塞的,单独设置一个名为stop
to的私有字段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
还是我可以使用其他一些技术来安全(但强制)处理所有内容?