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

时间:2011-06-17 09:08:15

标签: vb.net thread-safety

我是VB的新手,我正在尝试将一个帖子中的文本添加到我的Form1中的listview

我已尝试实施invokerequired方法,但新文本仍未添加到我的listview

(请参阅函数addlvDataItem

这是我在线程类中调用的:

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

这就是我在Form1类中所做的事情

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

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

1 个答案:

答案 0 :(得分:0)

您提供的代码会抛出TargetParameterCountException。 您必须将所有参数传递给您的委托子:

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

而不是

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