我正在尝试以单独的形式设置一个简单的TCP服务器到我的主服务器(在我测试的时候模拟一个arduino板)。
我有一个开始/停止按钮和一个显示服务器状态的标签。
我认为我最终已经正确处理了这些线程,但我仍然遇到一个异常,只有当我在线程运行时关闭表单时才会发生这种异常。我不确定为什么虽然因为线程是什么访问Label抛出异常而线程应该被关闭。
错误是:“在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