简体   繁体   中英

How to stop a blocking StreamReader.EndOfStream on a 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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM