title: C# Socket ReceiveAsync
body: <p>I am used to sync sockets and had a few headaches to get to the point where I am now, especially with <code>Socket.Receive(..)</code> not always receiveing all bytes</p>
  
  <p>Here is my code what I used to use</p>
  
  <pre><code>    public byte[] Receive(int size)
      {
          var buffer = new byte[size];
          var r = 0;
          do
          {
              // ReSharper disable once InconsistentlySynchronizedField
              var c = _clientSocket.Receive(buffer, r, size - r, SocketFlags.None);
              if (c == 0)
              {
                  throw new SocketExtendedException();
              }
              r += c;
          } while (r != buffer.Length);
          return buffer;
      }
  </code></pre>
  
  <p>Now I started to use sockets in Windows Phone BUT <code>.Receive(..)</code> is not available and I managed to get <code>Socket.ReceiveAsync(..)</code> working but I am concerned (no problems happened so far) here is my new code, I have not implemented the checking if all bytes has been recieved or not nor do I know if I have to with the following code</p>
  
  <pre><code>    private byte[] ReadBySize(int size = 4)
      {
          var readEvent = new AutoResetEvent(false);
          var buffer = new byte[size];
          var recieveArgs = new SocketAsyncEventArgs()
          {
              UserToken = readEvent
          };
          recieveArgs.SetBuffer(buffer, 0, size);
          recieveArgs.Completed += recieveArgs_Completed;
          _connecter.ReceiveAsync(recieveArgs);
          readEvent.WaitOne();
  
          if (recieveArgs.BytesTransferred == 0)
          {
              if (recieveArgs.SocketError != SocketError.Success)
                  throw new SocketException((int)recieveArgs.SocketError);
              throw new CommunicationException();
          }
          return buffer;
      }
  
      void recieveArgs_Completed(object sender, SocketAsyncEventArgs e)
      {
          var are = (AutoResetEvent)e.UserToken;
          are.Set();
      }
  </code></pre>
  
  <p>This is my first use of <code>ReceiveAsync</code> can someone point out anything I might have done wrong or need to change</p>