无法取消BackgroundWorker进程

时间:2013-12-13 12:19:30

标签: vb.net backgroundworker cancellation

我有一个BackgroundWorker,其中包含一个类ExcelOutput,用于将各种数据输出到工作簿,我应该立即提及bw.WorkerSupportsCancellation = True已设置。

在输出的每个阶段,我使用ExcelOutput检查Try/Catch中的错误,并在必要时显示错误(使用名为ErroReport()的函数。

结合错误消息,我想取消BackgroundWorker以避免进一步的错误。为此,我已将OutputWorker属性添加到ExcelOutput类,并将其设置为BackgroundWorker方法中bw_DoWork()的副本。

但是,ExcelOutput.ErroReport()中取消的操作无效,我不知道原因。

请注意,我测试了bw.CancellationPending的值,并在出错后将其设置为True。我还测试了下面的If条件是通过显示一个消息框来工作,这也有效。出于某种原因,似乎忽略了Exit Sub命令。

有谁能建议我做错了什么?感谢。

以下是设置bw_DoWork()BackgroundWorker函数的方法 -

Private Sub bw_DoWork(ByVal sender As Object,
                      ByVal e As DoWorkEventArgs)

    Dim Excel As New ExcelOutput  ' Create a new instance of the ExcelOutput class
    Dim CurrentRow As Integer = 4    ' Set the first output row

    '** Include a copy of the OutputWorker in the ExcelOutput (so that the OutputWorker can be cancelled)
    Excel.OutputWorker = Me

    If bw.CancellationPending = True Then
        e.Cancel = True
        Exit Sub
    Else
        Excel.Prepare()
    End If

    If bw.CancellationPending = True Then
        e.Cancel = True
        Exit Sub
    Else
        CurrentRow = Excel.OutputGroup("General", Headers, Data, 4)
    End If

    ' More stuff here...

End Sub

以下是设置ErrorReport()ExcelOutput函数的方法 -

Private Sub ErrorReport(ByVal Ex As Exception,
                        Optional ByVal CustomMessage As String = "")

    Call Me.ResetRange()    ' Destroy the 'Range' object
    Dim ErrorMessage As String = "Message: " & Ex.Message ' Set the default message
    If CustomMessage <> "" Then ErrorMessage = CustomMessage & vbCrLf & vbCrLf & Ex.Message
    Dim Result As Integer = MessageBox.Show(ErrorMessage,
                                            "An Error Has Occured",
                                            MessageBoxButtons.OK,
                                            MessageBoxIcon.Stop)

    '** Close the workbook (if it's open) and stop the OutputWorker *'
    Try
        Call Me.WB.Close(SaveChanges:=False)
        If Me.OutputWorker.WorkerSupportsCancellation = True Then
            Me.OutputWorker.CancelAsync()
        End If
    Catch
    End Try

End Sub

1 个答案:

答案 0 :(得分:1)

您应该尝试将DoWorkEventsArgs作为参数添加到ErrorReport函数中。

Private Sub ErrorReport(ByVal Ex As Exception,
                    Optional ByVal CustomMessage As String = "",
                    ByVal e As DoWorkEventsArgs)

Call Me.WB.Close(SaveChanges:=False)
    If e.WorkerSupportsCancellation = True Then
        e.CancelAsync()
    End If

您将可以取消背景工作。