我正在运行一名后台工作人员来读写文件。为了检查是否单击了取消按钮,我创建了一个名为“ check_bgWorkerCancelled()”的方法,该方法应该在取消挂起时处理所有事件。
当我单击取消按钮时,工作人员继续运行。当我单击开始按钮时,旧进程继续运行。
' Method: To check is cancellation is pending
Private Sub check_bgWorkerCancelled()
' check if cancellation is pending
If bgWorker_Scanner.CancellationPending = True Then
' background worker cancel asynchronous operating
If bgWorker_Scanner.IsBusy Then
Try 'try to
' cancel the threads
bgWorker_Scanner.CancelAsync()
' dispose the background worker
bgWorker_Scanner.Dispose()
Catch ex As Exception 'if exception
' invoke error
utils.invoke_msg(3, "Worker Error", ex.Message.ToString)
Me.Close() 'close form
End Try
End If
isScanning = False 'set scanning to false
Try
' invoke to bypass illegal cross threading UI update
BeginInvoke(CType(Sub()
progressBar1.Value = 0
txtStatus.Text = "Cancelled"
txtCalmDown.Text = ""
btnToggleScan.Image = Image.FromFile(Application.StartupPath & "/res/malware_scanner/rocket.png")
End Sub, MethodInvoker))
Catch ex As Exception : End Try
Else
Exit Sub
End If
End Sub
我尝试了以下解决方案,但没有一个起作用:
试图检查DoWork事件中是否已取消
Private Sub bgWorker_Scanner_DoWork(sender As Object, e As System.ComponentModel.DoWorkEventArgs) Handles bgWorker_Scanner.DoWork
If bgWorker_Scanner.CancellationPending = True Then
e.CancelAsync()
bgWorker_Scanner.dispose()
End If
End Sub
试图检查取消并收集垃圾
Private Sub bgWorker_Scanner_DoWork(sender As Object, e As System.ComponentModel.DoWorkEventArgs) Handles bgWorker_Scanner.DoWork
If bgWorker_Scanner.CancellationPending = True Then
e.CancelAsync()
bgWorker_Scanner.dispose()
GC.Collect()
End If
End Sub
试图在Try-Catch语句中执行上述操作
Private Sub bgWorker_Scanner_DoWork(sender As Object, e As System.ComponentModel.DoWorkEventArgs) Handles bgWorker_Scanner.DoWork
If bgWorker_Scanner.CancellationPending = True Then
If bgWorker_Scanner.IsBusy Then
Try
e.CancelAsync()
bgWorker_Scanner.dispose()
GC.Collect()
Catch ex As Exception
MsgBox(ex.Message.ToString)
End If
End If
End Sub
有什么方法可以结束后台工作,而不必完全关闭表单?任何帮助表示赞赏。