下面的代码是在全局代码中的,其中标红的是阻塞式的,如果没有客户端连接他会一直等。如何启动线程后,一直没等到客户端,但是又要停止线程?
Public Sub getData()
Dim ip As String = forms("Mainform").Controls("ip").text
Dim ipAddress As System.Net.IPAddress = System.Net.IPAddress.Parse(ip)
Dim port As Integer = 8081
Dim listener As New System.Net.Sockets.TcpListener(ipAddress, port)
listener.Start()
Dim clients As New System.Collections.Concurrent.ConcurrentDictionary(Of String, System.Net.Sockets.NetworkStream) ' 存储已连接的客户端及其网络流
Try
Do While True
'' 等待客户端连接,阻塞式的,如何停止
Dim client As System.Net.Sockets.TcpClient = listener.AcceptTcpClient()
'
........
.......
client.Close()
Loop
End Sub)
acceptThread.Start()
Catch ex As Exception
Forms("Mainform").Controls("TextBox_log").text= Forms("Mainform").Controls("TextBox_log").text & vbcrlf & "Error: " & ex.Message
Finally
' 确保监听器被关闭
listener.Stop()
End Try
End Sub
线程启动代码
Dim newthread As New System.Threading.Thread(AddressOf GetData)
vars("newthread") = newthread
newthread.IsBackground = True
newthread.Start()
停止线程代码,一执行这个代码整个foxtable程序就卡死了,因为那个阻塞的代码一直在等待。
If vars("newthread") IsNot Nothing Then
stoprfid = False ' 设置停止标志
vars("newthread").Abort
vars("newthread").Join() ' 等待线程结束
End If