Reputation: 2569
I serve various TCP clients asynchronously via their respective TCP sockets. Currently, I have 3 tasks running simultaneously:
NetworkStream
using await StreamReader.ReadAsync()
NetworkStream
using await StreamWriter.WriteAsync()
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
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
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