View Single Post
  #2 (permalink)  
Old 01-09-2009, 12:36 AM
jmcilhinney's Avatar
jmcilhinney jmcilhinney is offline
VB.NET Forum Moderator
.NET Framework: .NET 3.5 (VS 2008)
 
Join Date: Aug 2004
Location: Sydney, Australia
Age: 40
Posts: 6,125
Reputation: 542
jmcilhinney VB.NET gold medalistjmcilhinney VB.NET gold medalistjmcilhinney VB.NET gold medalistjmcilhinney VB.NET gold medalistjmcilhinney VB.NET gold medalistjmcilhinney VB.NET gold medalistjmcilhinney VB.NET gold medalistjmcilhinney VB.NET gold medalistjmcilhinney VB.NET gold medalistjmcilhinney VB.NET gold medalistjmcilhinney VB.NET gold medalist
Default

Whenever you have an issue the very first thing you should always do is read the relevant documentation. Sometimes it can be more difficult to identify what's the relevant documentation than others but the more experience you get the easier it will become.

The problem is arising because you're accessing your ListBox from the DataReceived event handler, which is executed in a background thread. This is from the MSDN documentation for the DataReceived event says this:
Quote:
The DataReceived event is raised on a secondary thread when data is received from the SerialPort object. Because this event is raised on a secondary thread, and not the main thread, attempting to modify some elements in the main thread, such as UI elements, could raise a threading exception. If it is necessary to modify elements in the main Form or Control, post change requests back using Invoke, which will do the work on the proper thread.
It provides a link to the documentation for the Control.Invoke method that shows you how to use it. Here's a condensed version that will work in your case:
Code:
Private Delegate Sub AddListBoxItemInvoker(ByVal item As Object)

Private Sub SerialPort1_DataReceived(ByVal sender As Object, _
                                     ByVal e As IO.Ports.SerialDataReceivedEventArgs) Handles SerialPort1.DataReceived
    Me.AddListBoxItem(Me.SerialPort1.ReadLine())
End Sub

Private Sub AddListBoxItem(ByVal item As Object)
    If Me.ListBox1.InvokeRequired Then
        'We are on a secondary thread so delegation is required.
        Me.ListBox1.Invoke(New AddListBoxItemInvoker(AddressOf AddListBoxItem), _
                           item)
    Else
        'We are on the primary thread so add the item.
        Me.ListBox1.Items.Add(item)
    End If
End Sub
Reply With Quote