Search code examples
.netmultithreadinglistviewinvokebasic

Reading information from a ListView from another thread in Visual Basic


I am having a problem reading an item from a ListView. The ListView is in the main thread, and the part where I read it out is in another class and another thread. My code is as follows:

Public Class Form1
    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        Dim ltm As ListViewItem = New ListViewItem
        ltm.Text = "test1"
        ltm.SubItems.Add("test2")
        ltm.SubItems.Add("test3")
        Me.ListView2.Items.Add(ltm)
        Dim l As New test
        Dim x As New Threading.Thread(AddressOf l.readout)
    End Sub
End Class
Public Class test
    Public Sub readout()
        For Each i As ListViewItem In Form1.ListView2.Items
            Dim command As String = i.SubItems(0).Text
            Dim value As String = i.SubItems(1).Text
            Dim executeon As String = i.SubItems(2).Text
            MsgBox(command & vbCrLf & value & vbCrLf & executeon)
        Next
    End Sub
End Class

I heard about invokes and found some sample code. I tried the following as well:

 Dim selectedItem = CStr((New Func(Of String)(Function() Form1.ListView2.Items(0).Text)).Invoke)
        MsgBox(selectedItem)

However, that did not work either. There are no error messages, it just does not show any messagebox. When I remove the threading and same class, it works just fine. Does anyone know why it does not work?


Solution

  • Basically, you can't touch the UI thread from another thread. It is hard to tell exactly what you are trying to do, but you could certainly check if you are on a non-UI thread and continue execution on the UI thread using InvokeRequired and BeginInvoke.

    Public Class Form1
    
        Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
            Dim ltm As ListViewItem = New ListViewItem
            ltm.Text = "test1"
            ltm.SubItems.Add("test2")
            ltm.SubItems.Add("test3")
            Me.ListView2.Items.Add(ltm)
            Dim l As New test(ListView2)
            Dim x As New Threading.Thread(AddressOf l.readout)
            x.Start()
        End Sub
    End Class
    
    Public Class test
    
        Public Sub New(listview As ListView)
            _listview = listview
        End Sub
    
        Private _listview As ListView
    
        Public Sub readout()
            If _listview.InvokeRequired Then
                _listview.BeginInvoke(New Action(AddressOf readout))
            Else
                For Each i As ListViewItem In Form1.ListView2.Items
                    Dim command As String = i.SubItems(0).Text
                    Dim value As String = i.SubItems(1).Text
                    Dim executeon As String = i.SubItems(2).Text
                    MsgBox(command & vbCrLf & value & vbCrLf & executeon)
                Next
            End If
        End Sub
    End Class