title: .Net SerialPort Readline Vs DataReceived Event Handler
body: <p>In VB.NET, what is the difference between using the SerialPort.ReadLine() method versus using the DataReceived event handler? Currently, I'm using the data received event handler and detecting the line endings. The problem is the data is coming in chunks and not 1 line sentences. If I use SerialPort.ReadLine() method, the data comes in 1 line sentences. Using this method, however, has the NewLine variable to set the line ending character for the port. Is the readline method just handling the buffer for me? Does the data still come in chunks regardless of the method used?</p>
  
  <p>Method 1:</p>
  
  <pre><code>While _continue
      Try 
          Dim message As String = _serialPort.ReadLine()
          Console.WriteLine(message)
      Catch generatedExceptionName As TimeoutException
      End Try 
  End While 
  </code></pre>
  
  <p>Method 2:</p>
  
  <pre><code>Public Sub StartListener()
      Try
  
          _serialport = New SerialPort()
          With _serialport
              .PortName = "COM3"
              .BaudRate = 38400
              .DataBits = 8
              .Parity = Parity.None
              .StopBits = StopBits.One
              .Handshake = Handshake.None
              AddHandler .DataReceived, AddressOf DataReceivedHandler
          End With
          _serialport.Open()
  
      Catch ex As Exception
      End Try
  End Sub
  
  Private Shared buffer As String = ""
  
  Private Sub DataReceivedHandler(sender As Object, e As SerialDataReceivedEventArgs)
      Try
          Dim rcv As String = _serialport.ReadExisting()
          buffer = String.Concat(buffer, rcv)
  
          Dim x As Integer
          Do
              x = buffer.IndexOf(vbCrLf)
              If x &gt; -1 Then
                  Console.WriteLine(buffer.Substring(0, x).Trim())
                  buffer = buffer.Remove(0, x + 2)
              End If
          Loop Until x = -1
      Catch ex as Exception
      End Try
  End Sub
  </code></pre>
  
  <p>I am currently using Method 2, but was thinking about switching to Method 1 because it seems safer and looks prettier you know, but what's the point? Thanks</p>