如何使用另一个类的线程正在接收的消息更新 GUI 中的数据?
我有一个带有从服务器接收数据的线程的类。每当从服务器收到消息时,该线程就会引发一个事件。此事件在 Starter 类(包含 GUI 的主类)中处理。事件处理程序(比如说DisplayData()
必须显示其他类收到的消息。我的代码是这样的
Class GUI
receiverObj = New Receiver()
Addhandler receiverObj.MessageAlert, Addressof DisplayData
...
...
Sub DisplayData()
Dim str As receiverObj.ReceiveData
lbEvents.Add.Items(str) ' lbEvents is a ListBox inside the GUI that displays messages from Receiver
End Sub
End Class
Class Receiver
Public Event MessageAlert()
Sub New ()
MyTcpClient = New TcpClient(hostIP, port)
MyTcpClient.GetStream.BeginRead(ReceiveData, 0, PacketSize, AddressOf ReceiveStream, Nothing)
End Sub
Public Sub ReceiveStream(ByVal ar As IAsyncResult)
Dim ByteCount As Integer
Try
ByteCount = MyTcpClient.GetStream.EndRead(ar)
Dim t As New Threading.Thread(Sub() RaiseEvent MessageAlert())
MyTcpClient.GetStream.BeginRead(ReceiveData, 0, PacketSize, AddressOf ReceiveStream, Nothing)
End Sub
End Class
Window 崩溃或挂起,并且列表框不显示数据。抛出异常说
跨线程操作无效:控件 xxx 从创建它的线程以外的线程访问。
任何人都可以提出解决此错误的方法吗?如何使用另一个类的线程正在接收的消息更新 GUI 中的数据?