Reputation: 381
I'm back again, with more code than last time. I may reference my previous questions here and there but this question is independent
I managed to convince my employer to drop the proprietary serial port communications library I was made to use, so now I am starting from scratch with SerialPorts and BackgroundWorkers so that I know how they work.
Here is my code:
Imports System
Imports System.IO.Ports
Public Class Form1
'SerialPort Port and BackgroundWorker Worker declared in form
Delegate Sub AppendText_Delegate(ByVal txtBox As TextBox, ByVal str As String)
Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
Port.PortName = ("COM9")
Port.BaudRate = 115200
Port.Parity = Parity.None
Port.StopBits = StopBits.One
Port.Handshake = Handshake.None
Port.ReadTimeout = 1000
Port.WriteTimeout = 1000
Port.Open()
AddHandler Port.DataReceived, AddressOf DataReceived
Worker.WorkerReportsProgress = True
Worker.WorkerSupportsCancellation = True
End Sub
Private Sub btnSend_Click(sender As System.Object, e As System.EventArgs) Handles btnSend.Click
Port.Write(txtInput.Text & vbCrLf)
End Sub
Private Sub DataReceived(sender As Object, e As SerialDataReceivedEventArgs)
Worker.RunWorkerAsync()
End Sub
Private Sub BackgroundWorker1_DoWork(sender As System.Object, e As System.ComponentModel.DoWorkEventArgs) Handles Worker.DoWork
If Worker.CancellationPending Then
e.Cancel = True
End If
AppendText_ThreadSafe(Me.txtOutput, Port.ReadLine())
End Sub
Private Sub AppendText_ThreadSafe(ByVal txtBox As TextBox, ByVal str As String)
If txtBox.InvokeRequired Then
Dim MyDelegate As New AppendText_Delegate(AddressOf AppendText_ThreadSafe)
Me.Invoke(MyDelegate, New Object() {txtBox, str})
Else
txtBox.AppendText(str)
End If
End Sub
End Class
At this moment I really not sure how the DataReceived
event and the BackgroundWorker
work together. Where should I put Worker.RunWorkerAsync()
so that it calls DoWork() only when the DataReceived
event is raised? Should I bind both events to the same method?
Thanks for your help, and apologies for the simplicity of this question. I've only just started with BackgroundWorkers and am still finding my footing, so to speak.
Upvotes: 0
Views: 220
Reputation: 8150
The DataReceived
event of the SerialPort
class is raised on a background thread, so it will not block the UI thread and you therefore don't need to use a BackgroundWorker
in this case. Because DataReceived
is called on a background thread, you will need to use Invoke
if you need to update any UI controls from that handler.
Upvotes: 2