我正在尝试取消我的后台工作人员WorkerClass.bw.CancelAsync()
。但这根本行不通。
//编辑!我在这里发布了完整的代码。希望这会有所帮助。
好的,我添加了一些消息框来了解工作人员是否仍然忙碌,并且有线的事情是,我得到一个false
当工人在做事的时候!?!?
Public Class Form1
Private Sub btn_start_click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btn_start.Click
Dim WorkerClass As New BGWClass
WorkerClass.bw.WorkerSupportsCancellation = True
WorkerClass.bw.WorkerReportsProgress = True
If btn_start.Text = "Start" Then
btn_start.Image = My.Resources.Resources.gem_remove
btn_add_addy.Enabled = False
btn_start.Text = "Stop"
WorkerClass.Start()
WorkerClass.bw.RunWorkerAsync()
MsgBox(WorkerClass.bw.IsBusy & " " & WorkerClass.bw.WorkerSupportsCancellation)
Else
btn_start.Image = My.Resources.Resources.error_fuck
btn_add_addy.Enabled = True
btn_start.Enabled = False
MsgBox(WorkerClass.bw.IsBusy & " " & WorkerClass.bw.WorkerSupportsCancellation)
WorkerClass.bw.CancelAsync()
End If
End Sub
End Class
Public Class BGWClass
Public bw As BackgroundWorker = New BackgroundWorker
Sub Start()
AddHandler bw.DoWork, AddressOf bw_DoWork
AddHandler bw.ProgressChanged, AddressOf bw_ProgressChanged
AddHandler bw.RunWorkerCompleted, AddressOf bw_RunWorkerCompleted
End Sub
Private Sub bw_DoWork(ByVal sender As Object, ByVal e As System.ComponentModel.DoWorkEventArgs)
For x As Integer = 1 To 15
If bw.CancellationPending Then
e.Cancel = True
Exit Sub
End If
bw.ReportProgress(x)
Threading.Thread.Sleep(1000)
Next
End Sub
Private Sub bw_ProgressChanged(ByVal sender As Object, ByVal e As System.ComponentModel.ProgressChangedEventArgs)
Dim myObject As Object = e.UserState
Form1.Prgs_error.Text = "- Error: " + e.ProgressPercentage.ToString
End Sub
Private Sub bw_RunWorkerCompleted(ByVal sender As Object, ByVal e As System.ComponentModel.RunWorkerCompletedEventArgs)
'...
End Sub
End Class
我认为你的问题是你只是在评估CancellationPending
一次,在你的开始时bw_DoWork
方法。因为实际上没有办法取消BackgroundWorker
在开始之前,CancellationPending
永远是假的,永远不会中断工作。当您调用时,BackgroundWorker 不会使用某种魔法来接管程序计数器CancelAsync
.
为了让它发挥作用,你的核心逻辑DoWork
方法必须以允许频繁轮询的方式实现CancellationPending
这样代码就能准确地知道何时退出它正在执行的操作。你需要从这里开始:
Private Sub bw_DoWork(ByVal sender As Object,
ByVal e As System.ComponentModel.DoWorkEventArgs)
If bw.CancellationPending = True Then
e.Cancel = True
Else
'do stuff here
End If
End Sub
对于更像这样的事情:
Private Sub bw_DoWork(ByVal sender As Object,
ByVal e As System.ComponentModel.DoWorkEventArgs)
Dim workIsCompleted As Boolean = False
While (Not bw.CancellationPending) AndAlso (Not workIsCompleted) Then
' Do stuff here, but incrementally so that the while loop can
' periodically check to see if CancelAsync has been called.
' Also, be sure to set workIsCompleted = True when the work is done.
' Otherwise, you will just spin forever until someone cancels it
' (Which may or may not be a bad thing, depending on your requirements)
End While
End Sub
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)