Private Sub Receiving(ByVal iAr As IAsyncResult)
Dim nChar As Integer
Dim newStr As String
Try
SyncLock client.GetStream
Try
nChar = client.GetStream.EndRead(iAr)
Catch
Console.WriteLine("exciting")
Exit Sub
End Try
End SyncLock
Catch ex As Exception
Console.WriteLine("exciting")
Exit Sub
End Try
newStr = Encoding.ASCII.GetString(bByte, 0, nChar)
TextBox3.Text = newStr
client.GetStream.BeginRead(bByte, 0, 4096, AddressOf Receiving, Nothing)
End Sub
我有这个代码,我正在尝试在文本框中写3我知道我需要使用委托,因为文本框在主线程中并且回调运行在单独的一个但是我如何创建我,我真的很困惑。我知道如何为一个简单的线程做到这一点,但因为这是我第一次使用异步回调,我不知道怎么做才能得到一些帮助
答案 0 :(得分:0)
您可以通过MSDN Thread-Safe call
对该解决方案进行检查首先需要创建一个方法来访问文本框,如下所示:
Private Sub SetText(ByVal [text] As String)
' InvokeRequired required compares the thread ID of the
' calling thread to the thread ID of the creating thread.
' If these threads are different, it returns true.
If Me.textBox3.InvokeRequired Then
Dim d As New SetTextCallback(AddressOf SetText)
Me.Invoke(d, New Object() {[text]})
Else
Me.textBox3.Text = [text]
End If
End Sub
然后你用你的线程方法调用它:
Private Sub Receiving(ByVal iAr As IAsyncResult)
Dim nChar As Integer
Dim newStr As String
Try
SyncLock client.GetStream
Try
nChar = client.GetStream.EndRead(iAr)
Catch
Console.WriteLine("exciting")
Exit Sub
End Try
End SyncLock
Catch ex As Exception
Console.WriteLine("exciting")
Exit Sub
End Try
newStr = Encoding.ASCII.GetString(bByte, 0, nChar)
SetText(newStr) ' Here you make the call
client.GetStream.BeginRead(bByte, 0, 4096, AddressOf Receiving, Nothing)
End Sub
希望这有帮助!