我试图找出解决这个问题的最佳方法。
我有一个BackgroundWorker被用来在定时器上建立套接字连接。
Public Shared AllUsersWorker As New BackgroundWorker
Public Shared AllUsersWorkerTimer As New DispatcherTimer
AllUsersWorkerTimer.Interval = TimeSpan.FromSeconds(2)
AllUsersWorkerTimer.Start()
AddHandler AllUsersWorkerTimer.Tick, AddressOf All_Users_Worker_Timer_Tick
Public Shared Sub All_Users_Worker_Timer_Tick()
AllUsersWorker.RunWorkerAsync()
End Sub
Public Shared Sub AllUsersWorker_DoWork(ByVal sender As Object, ByVal e As DoWorkEventArgs)
tcpClient = New TcpClient
tcpClient.Connect("localhost", 9999)
networkStream = tcpClient.GetStream
If networkStream.CanWrite And networkStream.CanRead Then
Read_All_Connections()
End If
tcpClient.Close()
End Sub我想启动BackgroundWorker线程,它建立TCP连接,读取/写入一些数据,然后关闭连接并每2秒重复一次。
我想每次物理地打开/关闭连接,因为有时我连接的服务器不发送数据,readByte调用暂停等待数据,并且在我重置程序之前进程无法继续(因此想要使用不同的线程到我的用户界面)。
此刻,我正在尝试使用间隔为2秒的DispatcherTimer来调用Worker.RunWorkerAsync。当调用RunWorkerAsync时,DoEvents方法运行 - 第一次工作正常,但后来的DispatcherTimer打勾的我发现前一个线程没有关闭,因此在调用RunWorkerAsync时我得到
"This BackgroundWorker is currently busy and cannot run multiple tasks
concurrently"
我能达到这个目标的最好方法是什么?
有没有更好的办法?
编辑:思考它。如果我能以某种方式构建一个看门狗,这将是一件好事,因此如果发现BackgroundWorker线程运行超过2秒钟,它将被终止,因为这表示线程已被tcp连接阻塞。
本