我无法从另一个线程访问列表框,并且在vb.net中不需要调用

时间:2015-08-06 19:28:44

标签: vb.net multithreading listbox

我希望有人可以帮助我。我试图从另一个线程访问一个列表框,而罕见的是invokerequired给了我" false",它假设能够直接访问它但没有任何反应,该项目没有添加到{ {1}}。

这是我的代码并提前致谢:

listbox

2 个答案:

答案 0 :(得分:1)

listenerThread方法中:

Private Sub listenerThread()
    While (True)
        counter += 1
        clientSocket = serverSocket.AcceptTcpClient()
        ThreadProcSafe("Client No: " & Convert.ToString(counter) & " IP: " & (IPAddress.Parse(CType(clientSocket.Client.RemoteEndPoint, IPEndPoint).Address.ToString())).ToString() & " Started!")

        Dim client1 As New FrmTCPServer ' *** THIS PLACE ***
        client1.startClient(clientSocket, Convert.ToString(counter))
    End While
End Sub

您创建新的FrmTCPServer表单,然后在新对象上调用startClient。所以你在新列表中添加数据没有这个正在运行的表单!

您应该将listenerThread方法更改为:

Private Sub listenerThread()
    While (True)
        counter += 1
        clientSocket = serverSocket.AcceptTcpClient()
        ThreadProcSafe("Client No: " & Convert.ToString(counter) & " IP: " & (IPAddress.Parse(CType(clientSocket.Client.RemoteEndPoint, IPEndPoint).Address.ToString())).ToString() & " Started!")

        Me.startClient(clientSocket, Convert.ToString(counter))
    End While
End Sub

答案 1 :(得分:0)

ThreadProcSafe方法更改为以下代码,然后重试:

Sub ThreadProcSafe(item As Object)
    If Lbconn.InvokeRequired Then
        Lbconn.Invoke(Sub() Lbconn.Items.Add(item))
    Else
        Lbconn.Items.Add(item)
    End If
End Sub