1
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 我知道我需要使用委托,因为文本框位于主线程中,而回调在单独的线程中运行,但我如何创建我,我真的使困惑。我知道如何为一个简单的线程执行此操作,但是由于这是我第一次使用异步回调,所以我不知道如何进行此操作,我能得到一些帮助吗

4

1 回答 1

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

希望这可以帮助!

于 2013-11-07T18:04:47.590 回答