Not quite certain how to implement multi-threading. I get a Debugger.Runtime.CrossThreadingMessagingException even if I invoked "Control.CheckForIllegalCrossThreadCalls = False" within the body of code. The code reacts to an unplugging of a USB dongle event, and I want to update a combobox SelectedIndex, but this is where the error results. The code below. Any direction on how to handle this would be greatly appreciated.
Code:
Public Sub USBRemoved_EventArrived(ByVal sender As Object, _
ByVal e As System.Management.EventArrivedEventArgs) _
Handles USBRemoved.EventArrived
Dim DeviceID As String
Dim RmComPort As String
Dim DeviceIndx As Integer
Dim Test
Control.CheckForIllegalCrossThreadCalls = False
Try
Dim smo As sm.ManagementBaseObject
smo = CType(e.NewEvent.Properties("TargetInstance").Value, _
sm.ManagementBaseObject)
'search through _USBDevices for Path retrieved from Dependent
Dim mp As New sm.ManagementPath(smo("Dependent").ToString)
Dim path As String = mp.RelativePath
path = path.Substring(path.IndexOf("=") + 2)
path = path.Substring(0, path.Length - 1)
If ((InStr(path, "VID_0403") <> 0) And (InStr(path, "PID_6001") <> 0)) Then
'CloseComPort()
Control.CheckForIllegalCrossThreadCalls = False
ParL2 = InStr(path, "PID_6001+") + 9
ParR2 = InStr(path, "\\0000")
If (ParR2 <> 0) Then
DeviceID = Microsoft.VisualBasic.Mid(path, ParL2, ParR2 - ParL2)
RmComPort = BTDevice(DeviceID) 'Report Associated ComPort to be Removed.
DeviceIndx = DeviceIndex(RmComPort)
myComPort.RemoveAt(DeviceIndex(RmComPort))
'Determine which index is impacted
USB_COMPORT2.Items.Remove(RmComPort)
USB_COMPORT2.SelectedIndex = USB_COMPORT2.Items.Count - 1 'This line is giving me the problem
DeviceIndex.Remove(BTDevice(DeviceID))
BTDevice.Remove(DeviceID)
End If
'to take off this limitation
'USB_COMPORT.Text = " "
BT_DETACH.Enabled = False
DevID.Text = " "
'RemoveHandler myComPort.DataReceived, AddressOf DataReceivedHandler
End If
For i As Integer = 0 To _USBDevices.Count - 1
With _USBDevices(i)
If .Path = mp.Path Then
BeginInvoke(USBChanged, New Object() _
{"Removed: " & .Info & _
If(.ExtraDescription <> "", "; " & .ExtraDescription, "") & vbCrLf})
_USBDevices.RemoveAt(i)
Exit For
End If
End With
Next i
Catch ex As Exception
Test = 1
End Try
End Sub