Acrotygma
Acrotygma

Reputation: 2569

TCP network stream handling

I serve various TCP clients asynchronously via their respective TCP sockets. Currently, I have 3 tasks running simultaneously:

  1. Await data from the NetworkStream using await StreamReader.ReadAsync()
  2. Write data into the NetworkStream using await StreamWriter.WriteAsync()
  3. Send watchdog messages periodically

Now, when I call something like this:

var stream = new NetworkStream(_socket);

// reading task

using (var reader = new StreamReader(stream)) {
    // ...read...
}

The underlying NetworkStream gets eventually destroyed after reading has been done because StreamReader closes it on Dispose().

The easiest way would be not closing the StreamReader, but AFAIK this is a very bad idea. So, how can I handle asynchronous reading and writing while keeping the socket connection open?

Upvotes: 2

Views: 532

Answers (2)

AgentFire
AgentFire

Reputation: 9780

Since the StreamReader will always dispose the underling stream on its own disposal (that's why actually it is IDisposable), you do indeed have to not close it until you have no need in the network stream anymore.

So, this is very ok for the situation:

var stream = new NetworkStream(_socket);
var reader = new StreamReader(stream);

And when you are finish, you would close both of them, right?

reader.Dispose();
stream.Dispose();

Upvotes: 0

Marc Gravell
Marc Gravell

Reputation: 1062520

From .NET 4.5 onwards, if you look through the constructor overloads for StreamReader and StreamWriter, there is one (and currently only one) constructor that takes a bool leaveOpen parameter. Use this overload and pass true - then it won't feel ownership of the underlying stream.

If this isn't available on your framework version, you'll have to create a NonClosingStream : Stream that decorates a stream using pass-thru implementations for everything except Close() and Dispose(), which should be no-ops (well, they could assign null to the field that represents the wrapped stream, but nothing more).

Upvotes: 2

Related Questions