2013-08-31 74 views
1

我的意圖與下面的代碼是開始尋找(異步)爲UDP數據報,當我的窗體打開。當收到數據報時,我想要做的就是調用在主線程上運行的過程(傳遞收到的消息),然後重新開始查找另一個數據報。假設代碼是正確的,直到數據報出現,我如何執行接下來的兩個步驟?我對跨線程操作,代表等感到非常困惑。謝謝。另外,我想留在.NET 4.0中。如何在Windows窗體應用程序(VB.NET)中使用UdpClient.BeginReceive

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 

回答

4

您的UDPRecv()方法將在I/O完成線程上運行。任何嘗試從該線程更新UI都會炸燬您的程序。您必須使用表單的BeginInvoke()方法將字符串傳遞給在UI線程上運行的方法。當程序終止時,您還必須處理關閉的套接字,這需要捕獲EndReceive()調用將拋出的ObjectDisposedException。

因此,使它看起來像這樣:

Public Sub UDPRecv(ar As IAsyncResult) 
    Try 
     '' Next statement will throw when the socket was closed 
     Dim recvBytes As Byte() = dgClient.EndReceive(ar, SiteEndPoint) 
     Dim recvMsg As String = Encoding.UTF8.GetString(recvBytes) 
     '' Pass the string to a method that runs on the UI thread 
     Me.BeginInvoke(New Action(Of String)(AddressOf DataReceived), recvMsg) 
     '' Continue receiving 
     dgClient.BeginReceive(AddressOf UDPRecv, Nothing) 
    Catch ex As ObjectDisposedException 
     '' Socket was closed, do nothing 
    End Try 
End Sub 

Private Sub DataReceived(recvMsg As String) 
    '' This method runs on the UI thread 
    '' etc... 
End Sub 

Private Sub Form1_FormClosing(sender As Object, e As FormClosingEventArgs) Handles MyBase.FormClosing 
    '' Close the socket when the form is closed 
    dgClient.Close() 
End Sub 
+0

謝謝你,漢斯。我把下面的地方放在''等等......:Debug.WriteLine(recvMsg)和me.TextBox1.text = recvMsg。調試行顯示消息,但文本框不更新。 – John

+0

我的錯誤。它效果很好。這很簡單。再次感謝。 – John

相關問題