【问题标题】:Cannot cancel a BackgroundWorker procss无法取消 BackgroundWorker 进程
【发布时间】:2014-01-01 05:08:56
【问题描述】:

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

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

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

但是,在ExcelOutput.ErroReport() 中进行的取消不起作用,我不知道为什么。

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

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

下面是 BackgroundWorker 类中的 bw_DoWork() 函数的设置方式 -

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

下面是 ExcelOutput 类中的 ErrorReport() 函数的设置方式 -

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

【问题讨论】:

    标签: vb.net backgroundworker cancellation


    【解决方案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
    

    您将能够取消 Backgroundworker。

    【讨论】:

    • 谢谢,但我也得到了同样的结果。
    猜你喜欢
    • 2015-01-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-10-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多