2

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?

1
  • 1
    As a minor observation: I do a lot of socket work, and a lot of binary protocol work; I never ever use StreamReader / StreamWriter, because frankly they don't add much - you might want to consider just working directly off the Stream Commented Nov 28, 2013 at 9:36

2 Answers 2

2

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).

Sign up to request clarification or add additional context in comments.

Comments

0

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();

2 Comments

in .NET 4.5, both reader and writer have "and optionally leaves the stream open." support, so it is not true that they "will always dispose the underlying stream"
@MarcGravell very well.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.