无法等待BackgroundWorker CancelAsync

时间:2018-04-21 07:35:35

标签: vb.net winforms async-await backgroundworker

我的项目中有一个BackgroundWorker,我想在一个方法中重启。但是,当我使用CancelAsync()方法然后立即使用RunWorkerAsync()方法时,取消尚未完成,并且启动了2个BackgroundWorker实例并抛出了InvalidOperationException。为了解决这个问题,我将方法设为异步(它是一个Sub方法)并等待CancelAsync()等待它完成。但是,这会返回表达式不会产生值的错误。这是由于呼叫还是工人的方法?

工人方法:

Private Sub GIFworker(sender As Object, e As System.ComponentModel.DoWorkEventArgs) Handles bkwGIF.DoWork
        Dim hum As Integer = e.Argument
        If hum Mod 2 = 1 Then
            While bkwGIF.CancellationPending = False
                pbxRpsHum.Image = ilRPS.Images(0)
                Thread.Sleep(1000)
                pbxRpsHum.Image = ilRPS.Images(1)
                Thread.Sleep(1000)
            End While
        Else
            While bkwGIF.CancellationPending = False
                pbxRpsHum.Image = ilRPS.Images(0)
                Thread.Sleep(1000)
                pbxRpsHum.Image = ilRPS.Images(3)
                Thread.Sleep(1000)
            End While
        End If
    End Sub

调用CancelAsync()(哼声是一个整数):

Await bkwGIF.CancelAsync()
bkwGIF.RunWorkerAsync(hum)

1 个答案:

答案 0 :(得分:0)

以下是取消Call magic helper that will upload an attachment

的示例
BackgroundWorker

如果要在取消时重新启动后台工作,那么当您检测到Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load 'Raise the DoWork event in a worker thread. Me.BackgroundWorker1.RunWorkerAsync() End Sub 'This method is executed in a worker thread. Private Sub BackgroundWorker1_DoWork(sender As Object, e As DoWorkEventArgs) Handles BackgroundWorker1.DoWork Dim worker As BackgroundWorker = DirectCast(sender, BackgroundWorker) For i As Integer = 1 To 100 If worker.CancellationPending Then 'The user has cancelled the background operation. e.Cancel = True Exit For End If 'Raise the ProgressChanged event in the UI thread. worker.ReportProgress(i, i & " iterations complete") 'Perform some time-consuming operation here. Threading.Thread.Sleep(250) Next i End Sub 'This method is executed in the UI thread. Private Sub BackgroundWorker1_ProgressChanged(sender As Object, e As ProgressChangedEventArgs) Handles BackgroundWorker1.ProgressChanged Me.ProgressBar1.Value = e.ProgressPercentage Me.Label1.Text = TryCast(e.UserState, String) End Sub 'This method is executed in the UI thread. Private Sub BackgroundWorker1_RunWorkerCompleted(sender As Object, e As RunWorkerCompletedEventArgs) Handles BackgroundWorker1.RunWorkerCompleted If e.Cancelled Then 'The background operation was cancelled. Me.Label1.Text = "Operation cancelled" Else 'The background operation completed normally. Me.Label1.Text = "Operation complete" End If End Sub Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click 'Only cancel the background opertion if there is a background operation in progress. If Me.BackgroundWorker1.IsBusy Then Me.BackgroundWorker1.CancelAsync() End If End Sub RunWorkerCompleted时,您会在e.Cancelled事件处理程序中重新启动。