Vb.net 从线程向列表视图添加文本

Vb.net 从线程向列表视图添加文本,vb.net,thread-safety,Vb.net,Thread Safety,我是VB新手,我正在尝试将线程中的文本添加到Form1中的listview中 我已经尝试实现invokerequired方法,但新文本仍然没有添加到我的listview中 请参阅函数addlvDataItem 这就是我在thread类中所说的: Private Sub DoServerListening() 'Thread to listen for new incoming socket clients Dim mSocket As System.Net.Sockets.Soc

我是VB新手,我正在尝试将线程中的文本添加到Form1中的listview中

我已经尝试实现invokerequired方法,但新文本仍然没有添加到我的listview中

请参阅函数addlvDataItem

这就是我在thread类中所说的:

Private Sub DoServerListening()
    'Thread to listen for new incoming socket clients
    Dim mSocket As System.Net.Sockets.Socket
    Dim newConnectionThread As clsTCPConnection
    Dim strRemoteIPAddress As String

    Do
        Try
            While bServerRunning = True
                If mTCPListener.Pending = True Then

                    mSocket = mTCPListener.AcceptSocket()
                    'mSocket.Blocking = True
                    If mSocket.Connected Then
                        strRemoteIPAddress = Split(mSocket.RemoteEndPoint.ToString, ":")(0)
                        newConnectionThread = New clsTCPConnection(mSocket, strRemoteIPAddress)
                        'Start the thread to handle this connection
                        Form1.addlvDataItem("Connected to " & strRemoteIPAddress.ToString(), 0)
                        Dim myThread As New System.Threading.Thread(AddressOf newConnectionThread.HandleConnection)
                        myThread.Start()
                    End If
                End If

            End While
        Catch ex As Exception
            If bServerRunning = True Then
                'notify main application

            End If
        End Try

    Loop

End Sub
这就是我在一年级时做的

Public Delegate Sub addlvDataItemCallback(ByVal [text] As String, ByVal Num As Integer)

Public Sub addlvDataItem(ByVal [text] As String, ByVal Type As Integer)
    CurrentDateTime = DateTime.Now

    If lvData.InvokeRequired Then
        Dim d As New addlvDataItemCallback(AddressOf addlvDataItem)
        Me.Invoke(d, New Object() {[text]})
    Else
        If Type = 1 Then 'TX
            Me.lvData.Items.Add("TX (" + text.Length.ToString() + " bytes): " + CurrentDateTime + " : <Start> " + text.ToString() + "<End>")
        ElseIf Type = 2 Then
            Me.lvData.Items.Add("RX (" + text.Length.ToString() + " bytes): " + CurrentDateTime + " : <Start> " + text.ToString() + "<End>")
        Else
            Me.lvData.Items.Add("Info: " + CurrentDateTime + " : " + text.ToString())

        End If
    End If
End Sub

我添加的新文本不会显示在listview中。我没有得到任何编译或运行时错误,但仍然没有新的文本列表框。我可以从Form1类中添加文本,但不能从线程中添加文本。

您提供的代码确实会引发TargetParameterCountException。 必须将所有参数传递给代理子系统:

Me.Invoke(d, New Object() {[text], Type})
而不是

Me.Invoke(d, New Object() {[text]})