In VB.NET, what is the difference between using the SerialPort.ReadLine () method and using a DataReceived event handler? I am currently using a processed data handler and detect line endings. The problem is that the data comes in chunks, not in 1 line of sentences. If I use the SerialPort.ReadLine () method, the data comes in 1 line of sentences. However, using this method has a NewLine variable to set the line termination character for the port. Does the readline method just process the buffer for me? Are data stored in chunks regardless of the method used?
Method 1:
While _continue Try Dim message As String = _serialPort.ReadLine() Console.WriteLine(message) Catch generatedExceptionName As TimeoutException End Try End While
Method 2:
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 > -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
I'm currently using method 2, but was thinking of switching to method 1 because it seems more secure and looks prettier than you know, but what's the point? Thanks
source share