I serve various TCP clients asynchronously via their respective TCP sockets. Currently, I have 3 tasks running simultaneously:
- Await data from the
NetworkStreamusingawait StreamReader.ReadAsync() - Write data into the
NetworkStreamusingawait StreamWriter.WriteAsync() - 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?
StreamReader/StreamWriter, because frankly they don't add much - you might want to consider just working directly off theStream