收到tcp / ip响应后,Visual Basic窗体冻结

时间:2014-12-29 01:36:26

标签: vb.net forms button tcpclient visual-studio-2015

我在Linux主机上的Python和Windows主机上的Visual Basic之间建立了基本的TCP / IP通信设置。 Windows主机似乎工作正常,作为测试,我向Linux机器发送0并让它以0打印到Visual Basic调试控制台。一切正常,但在Visual Basic收到响应并成功显示后,它会冻结表单,因此我无法按下另一个按钮。这是代码的一个例子。

Imports System.Net
Imports System.Net.Sockets
Imports System.Text

Public Class Form1
    Shared Sub Main()
        Dim tcpClient As New System.Net.Sockets.TcpClient()
        tcpClient.Connect("192.168.60.124", 9999)
        Dim networkStream As NetworkStream = tcpClient.GetStream()
        If networkStream.CanWrite And networkStream.CanRead Then
            ' Do a simple write.
            Dim sendBytes As [Byte]() = Encoding.ASCII.GetBytes("0")
            networkStream.Write(sendBytes, 0, sendBytes.Length)
            ' Read the NetworkStream into a byte buffer.
            Dim bytes(tcpClient.ReceiveBufferSize) As Byte
            networkStream.Read(bytes, 0, CInt(tcpClient.ReceiveBufferSize))
            ' Output the data received from the host to the console.
            Dim returndata As String = Encoding.ASCII.GetString(bytes)
            Console.WriteLine(("Host returned: " + returndata))
            tcpClient.Close()
        Else
            If Not networkStream.CanRead Then
                Console.WriteLine("cannot not write data to this stream")
                tcpClient.Close()
            Else
                If Not networkStream.CanWrite Then
                    Console.WriteLine("cannot read data from this stream")
                    tcpClient.Close()
                End If
            End If
        End If
    End Sub

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Main()
    End Sub
End Class   

1 个答案:

答案 0 :(得分:3)

自OP请求以来,我提出了我的评论,作为我的回答^^

的一部分

请参阅Multi-threading and Console.WriteLine

“很多人使用Console.WriteLine作为登录多线程程序。但实际上,它会使事情变慢。控制台I / O流同步,即阻止我/ O操作。每当多个线程使用Console.WriteLine时,只有一个线程可以进行I / O操作,而其他线程需要等待

我想知道这就是Console.WriteLine阻止UI的原因吗?


原帖

我想知道你需要做Multithreaded Programming with Visual Basic .NET。因为您在主线程(UI线程)中具有TCP客户端活动。因此,除非完成TCP客户端活动,否则您无法在UI上执行任何操作,例如按钮单击。

我的建议是将您的TCP客户端活动放入一个函数中,并在单击button1后启动另一个线程来继续它。

Sub Tcpclient()
    ' The statement of TCPClient function
End Sub

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    Dim tcpClientThread As New System.Threading.Thread( _
        AddressOf Tcpclient)
    tcpClientThread.Start()
End Sub