【发布时间】:2017-07-13 05:19:27
【问题描述】:
在 winform 程序中使用后台工作程序。还与一些设备通信
我有一个停止按钮,它试图停止后台工作线程,它可以工作,但有时,后台工作线程仍处于“已中止”状态
我不得不提一下,我会注意出现的异常,并且还使用“Finally”块来停止与设备的通信
我需要立即停止线程,比如紧急按钮...
一些代码:
Private Sub BtnStopTest_Click(sender As Object, e As EventArgs) Handles btnStopTest.Click
Try
stoppedTesting = True
Log("Stopping operations safely. (You might have to wait some time )", Color.Blue, New Font("Microsoft Sans Serif", 9, FontStyle.Bold))
If bgWorkThread IsNot Nothing Then
'stop thread
'if thread is sleeping (waiting for a time)
If bgWorkThread.ThreadState = ThreadState.Background + ThreadState.WaitSleepJoin Then
bgWorkThread.Interrupt()
Else 'if thread is working normally
bgWorker.CancelAsync()
tEO.DoWorkEventArgs.cancel = True
bgWorkThread.Abort()
'sometimes, here the Thread has state 'Aborted
End If
ElseIf bgWorkThread Is Nothing Then
Dim ee As New System.ComponentModel.RunWorkerCompletedEventArgs(New Object, Nothing, False)
BgWorker_RunWorkerCompleted(New Object, ee)
End If
Catch ex As Exception
Utils.PreserveStackTrace(ex)
Log("Error when stopping testing" & vbCrLf & Utils.ReadException(ex), MessageType.ErrorMessage)
End Try
End Sub
Private Sub BgWorker_DoWork(sender As Object, e As System.ComponentModel.DoWorkEventArgs) Handles bgWorker.DoWork
Try
'some other things to do
For Each testStep In stepList
Try
'main operations and communication with device
' below functions are all different
'something like:
'CommunicationWithDevice1()
'CommunicationWithDevice2()
'CommunicationWithDevice3()
'CommunicationWithDevice4()
'....
'CommunicationWithDevice20()
Catch ex As Exception When TypeOf ex Is ThreadAbortException OrElse TypeOf ex Is ThreadInterruptedException
Utils.PreserveStackTrace(ex)
Log("Exception in thread" & vbCrLf & Utils.ReadException(ex), MessageType.ErrorMessage)
e.Cancel = True
If ex.GetType = GetType(ThreadAbortException) Then Thread.ResetAbort()
If stoppedTesting Then Exit For
Catch ex As Exception
If stoppedTesting Then Exit For
End Try
Catch ex As Exception When TypeOf ex Is ThreadAbortException OrElse TypeOf ex Is ThreadInterruptedException
e.Cancel = True
Log("Background worker thread was interrupted!")
Log("Background worker thread was interrupted!", Color.Red, New Font("Microsoft Sans Serif", 9, FontStyle.Bold))
Catch ex As Exception
Utils.PreserveStackTrace(ex)
Log("Error when doing background work!" & vbCrLf & Utils.ReadException(ex), Color.Red, New Font("Microsoft Sans Serif", 9, FontStyle.Bold))
Finally
StopCommunication()
End Try
End Sub
- 我可以做些什么来完全销毁线程?
- 如果不可能,是否有任何解决方法可以立即退出我的“DoWork”方法?
【问题讨论】:
-
哎哟! Bgw 使用 Pool 线程,你甚至不应该改变它的任何属性,当然也不应该 Abort() 它!
-
您不能也不应该处置或销毁线程。他们照顾自己。
-
@HenkHolterman 好的...您对紧急停止线程有什么想法吗?
-
是的,避免需要。请参阅this 等等。应该避免为您自己的线程使用 Thread.Abort(),在池线程上调用它是......邪恶的。
标签: vb.net multithreading