title: C#, Async Tasks and NetworkStream.BeginRead, how to guarantee the buffer won't be overwritten?
body: <p>I'm trying to write a piece of code in C# to read from a TcpClient asynchronously. Here's my code:</p>
  
  <pre><code>using System;
  using System.Net;
  using System.Net.Sockets;
  using System.Threading.Tasks;
  
  class Connection
  {
      private TcpClient socket;
      private NetworkStream socketStream;
      private byte[] buffer;
      private int bytesRead;
      private Task&lt;int&gt; readTask;
  
      public Connection(TcpClient socket)
      {
          this.socket = socket;
          socketStream = socket.GetStream();
          buffer = new byte[4096];
  
          readTask = Task.Factory.FromAsync&lt;byte[], int, int, int&gt;(
              this.socketStream.BeginRead
              , this.socketStream.EndRead
              , this.buffer
              , 0
              , this.buffer.Length
              , null
          );
          readTask.ContinueWith(
              (task) =&gt; {
                  this.bytesRead = (int)task.Result;
                  //Do something with buffer.
              }
              , TaskContinuationOptions.OnlyOnRanToCompletion
          );
      }
  }
  </code></pre>
  
  <p>The problem is that the asynchronous BeginRead will try to write over the Connection object's buffer and once a new data arrives the old one will be overwritten regardless of whether it is consumed or not. How should I tackle this problem? AFAIK it should have something to do with closures but I can't figure it out how!</p>