我使用下面的代码的目的是在我的表单打开时开始(异步)查找 UDP 数据报。当收到数据报时,我想做的就是调用一个在主线程上运行的过程(传递接收到的消息),然后重新开始寻找另一个数据报。假设代码在数据报显示之前是正确的,我该如何执行接下来的两个步骤?我真的对跨线程操作、委托等感到困惑。谢谢。另外,我想继续使用 .Net 4.0。
Const RcvPort As Integer = 33900
Public RRWEndPoint As IPEndPoint = New IPEndPoint(myIPaddr, RcvPort)
Public SiteEndPoint As IPEndPoint = New IPEndPoint(IPAddress.Any, RcvPort)
Public dgClient As UdpClient = New UdpClient(RRWEndPoint)
Private Sub Form1_Load(sender As Object, e As System.EventArgs) Handles Me.Load
dgClient.BeginReceive(AddressOf UDPRecv, Nothing)
End Sub
Public Sub UDPRecv(ar As IAsyncResult)
Dim recvBytes As Byte() = dgClient.EndReceive(ar, SiteEndPoint)
Dim recvMsg As String = Encoding.UTF8.GetString(recvBytes)
dgClient.BeginReceive(AddressOf UDPRecv, Nothing)
End Sub