title: Constantly read from NetworkStream async
body: <p>I am a farily new .NET-developer and I'm currently reading up on <code>async</code>/<code>await</code>. I need to work on a framework used for testing devices that are controlled by remotely accessing servers using TCP and reading/writing data from/to these servers. This will be used for unit tests.</p>
  
  <p>There is no application-layer protocol and the server may send data based on external events. Therefore I must be able to continuously capture any data coming from the server and write it to a buffer, which can be read from a different context.</p>
  
  <p>My idea goes somewhere along the lines of the following snippet:</p>
  
  <pre><code>// ...
  private MemoryStream m_dataBuffer;
  private NetworkStream m_stream;
  // ...
  
  public async void Listen()
  {
    while (Connected)
    {
      try
      {
        int bytesReadable = m_dataBuffer.Capacity - (int)m_dataBuffer.Position;
  
        // (...) resize m_dataBuffer if necessary (...)
  
        m_stream.ReadTimeout = Timeout;
  
        lock (m_dataBuffer)
        {
          int bytesRead = await m_stream.ReadAsync(m_dataBuffer.GetBuffer(), 
            (int)m_dataBuffer.Position, bytesReadable);
          m_stream.Position += bytesRead;
        }
      }
      catch (IOException ex)
      {
        // handle read timeout.
      }
      catch (Exception)
      {
        throw new TerminalException("ReadWhileConnectedAsync() exception");
      }
    }
  }
  </code></pre>
  
  <p>This seems to have the following disadvantages:</p>
  
  <ol>
  <li>If calling and awaiting the <code>Listen</code> function, the caller hangs, even though the caller must be able to continue (as the network stream should be read as long as the connection is open).</li>
  <li>If declaring it <code>async void</code> and not awaiting it, the application crashes when exceptions occur in the Task. </li>
  <li>If declaring it <code>async Task</code> and not awaiting it, I assume the same happens (plus I get a warning)?</li>
  </ol>
  
  <p>The following questions ensue:</p>
  
  <ul>
  <li>Can I catch exceptions thrown in <code>Listen</code> if I don't await it?</li>
  <li>Is there a better way to constantly read from a network stream using <code>async</code>/<code>await</code>? </li>
  <li>Is it actually sane to try to continuously read from a network stream using <code>async</code>/<code>await</code> or is a thread a better option?</li>
  </ul>