从 Visual Basic 中的另一个线程的 ListView 中读取信息

Reading information from a ListView from another thread in Visual Basic

我在从 ListView 读取项目时遇到问题。 ListView在主线程,我读出来的部分在另一个class和另一个线程。我的代码如下:

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

我听说过调用并找到了一些示例代码。我也尝试了以下方法:

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

然而,这也没有用。没有错误消息,它只是不显示任何消息框。当我删除线程和相同的 class 时,它工作得很好。有谁知道为什么它不起作用?

基本上,您不能从另一个线程触及 UI 线程。很难确切地说出您要做什么,但是您当然可以检查您是否在非 UI 线程上并使用 InvokeRequired 和 BeginInvoke 在 UI 线程上继续执行。

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