title: Read ASync Network Stream
body: <p>I've done a fair amount of searching and I'm sure I'm close, but I'm having problems and hoping someone can help.</p>
  
  <p>I have an ethernet barcode scanner I need to be listening to constantly. I've tried using <code>NetworkStream</code>.Read in a separate thread, but then found out there is a '<code>BeginRead</code>' function for async network streams. Problem is I can't get it working at all.</p>
  
  <p>Here's the code I've got:</p>
  
  <pre><code>Public Class ScannerConnect
      Private client As TcpClient
      Property server As String
      Property port As Int32 = 2005
      Private data As [Byte]()
  
  
      Sub Connect()
          Try
              client = New TcpClient(server, port)
          Catch e As ArgumentNullException
             Console.WriteLine("ArgumentNullException: {0}", e)
          Catch e As SocketException
              Console.WriteLine("SocketException: {0}", e)
          End Try
      End Sub 'Connect
  
      Sub ListenASync()
          stream = client.GetStream()
          data = New [Byte](256) {}
          stream.BeginRead(data, 0, data.Length, AddressOf ReadASync, stream)
      End Sub
  
      Private Sub ReadASync(ar As IAsyncResult)
          Dim buffer As Byte() = TryCast(ar.AsyncState, Byte())
          Dim bytesRead As Integer = stream.EndRead(ar)
          Dim message As String = Encoding.ASCII.GetString(buffer, 0, bytesRead)
  
          MsgBox(message)
  
          stream.BeginRead(buffer, 0, buffer.Length, AddressOf ReadASync, buffer)
      End Sub
  End Class
  </code></pre>
  
  <p>It crashes on 
      Dim message As <code>String = Encoding.ASCII.GetString(buffer, 0, bytesRead)</code>
  with error
      <code>Array</code> cannot be <code>null</code>.</p>
  
  <p>Any ideas what I'm doing wrong?</p>