| VB.NET |如果在单独的线程中调用计时器,则计时器不会启动

时间:2018-07-09 15:39:17

标签: vb.net multithreading tcp timer

我正在尝试建立TCP连接客户端服务器,为此,我使用计时器对接收到的消息进行轮询。 代码如下:

Imports System.Net
Imports System.Net.Sockets
Imports System.Threading

Public Class Form1

Dim TCPServer As Socket
Dim TCPListenerz As TcpListener
Friend WithEvents Timer1 As Windows.Forms.Timer

Sub listenthread()
    TCPListenerz = New TcpListener(IPAddress.Any, 1000)
    TCPListenerz.Start()
    TCPServer = TCPListenerz.AcceptSocket()
    TCPServer.Blocking = False
    Button2.BackColor = Color.LawnGreen
    Timer1.Start()
End Sub

Dim listen As New Thread(AddressOf listenthread)

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click

    Dim sendbytes() As Byte = System.Text.Encoding.ASCII.GetBytes(TextBox2.Text)
    TCPServer.Send(sendbytes)

End Sub

Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer1.Tick
    Try
        Dim rcvbytes(TCPServer.ReceiveBufferSize) As Byte
        TCPServer.Receive(rcvbytes)
        TextBox3.Text = System.Text.Encoding.ASCII.GetString(rcvbytes)
    Catch ex As Exception
    End Try

End Sub

Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    listen.Start()
End Sub
End Class

问题在于,即使侦听线程正确启动,计时器也不会启动。 更奇怪的是,如果我在主线程的按钮的click事件中使用了listenthread的相同代码,则计时器将正确启动:

Imports System.Net
Imports System.Net.Sockets
Imports System.Threading

Public Class Form1

Dim TCPServer As Socket
Dim TCPListenerz As TcpListener
Friend WithEvents Timer1 As Windows.Forms.Timer

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click

    Dim sendbytes() As Byte = System.Text.Encoding.ASCII.GetBytes(TextBox2.Text)
    TCPServer.Send(sendbytes)

End Sub

Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click

TCPListenerz = New TcpListener(IPAddress.Any, 1000)
TCPListenerz.Start()
TCPServer = TCPListenerz.AcceptSocket()
TCPServer.Blocking = False
Button2.BackColor = Color.LawnGreen
Timer1.Enabled = True

End Sub

Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer1.Tick
    Try
        Dim rcvbytes(TCPServer.ReceiveBufferSize) As Byte
        TCPServer.Receive(rcvbytes)
        TextBox3.Text = System.Text.Encoding.ASCII.GetString(rcvbytes)
    Catch ex As Exception
    End Try

End Sub

End Class

为什么在其他线程中调用计时器后计时器不启动?

0 个答案:

没有答案