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.s开发者_如何转开发tream);
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?
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.
精彩评论