我正在尝试以与我的主要服务器不同的形式设置一个简单的 TCP 服务器(在我测试时模拟一个 arduino 板)。
我有一个开始/停止按钮和一个显示下方服务器状态的标签。
我想我终于正确处理了这些线程,但我仍然遇到一个异常,该异常仅在我在线程运行时关闭表单时发生。我不知道为什么因为线程是访问引发异常的标签并且线程应该关闭的原因。
错误是:在 UpdateStatus() 中的“Me.Invoke(d, New Object() {status})”行中的“System.Windows.Forms.dll 中发生了‘System.ObjectDisposedException’类型的第一次机会异常”
代码在下面,我发现了应该完成这项工作的异常,但我想知道我是否做错了什么。任何建议将不胜感激,谢谢
Imports System.Net
Imports System.Net.Sockets
Imports System.Threading
Public Class ArduinoSimulator
Dim running As Boolean = False
Dim serverThread As New Threading.Thread(AddressOf StartServer)
Private Sub startserver()
While (running)
Dim time As String = DateTime.Now.Second.ToString
updateStatus(time)
End While
End Sub
Private Sub StartStop_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles StartStop.Click
If Not running Then
running = True
updateButton("Stop Simulation")
Dim serverThread As New Threading.Thread(AddressOf startserver)
serverThread.IsBackground = True
serverThread.Start()
Else
running = False
updateButton("Start Simulation")
updateStatus("Not Started")
Try
serverThread.Abort()
Catch ex As Exception
End Try
End If
End Sub
Delegate Sub UpdateStatusCallback(ByVal status As String)
Private Sub updateStatus(ByVal status As String)
Try
If Me.InvokeRequired Then
Dim d As New UpdateStatusCallback(AddressOf updateStatus)
Me.Invoke(d, New Object() {status})
Else
StatusLabel.Text = status
End If
Catch ex As Exception
End Try
End Sub
Delegate Sub UpdateButtonCallback(ByVal buttontext As String)
Private Sub updateButton(ByVal buttontext As String)
If Me.InvokeRequired Then
Dim d As New UpdateStatusCallback(AddressOf updateStatus)
Me.Invoke(d, New Object() {buttontext})
Else
StartStop.Text = buttontext
End If
End Sub
Private Sub ArduinoSimulator_close(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Me.FormClosing
Main.ArduinoConnectionSimulatorToolStripMenuItem.Checked = False
running = False
Try
serverThread.Abort()
Catch ex As Exception
End Try
End Sub
End Class