如果在另一个模块中运行,则为BackgroundWorker.ReportProgress异常

时间:2012-03-18 20:57:23

标签: vb.net backgroundworker

我的BackgroundWorker在我的主要形式frmMain中完美运行。但是当我在另一个模块中运行ReportProgress方法时,我得到异常“这个BackgroundWorker声明它不报告进度。修改WorkerReportsProgress以声明它确实报告进度。”这个IS用于报告进度;这在主模块中以相同的方式运行时工作正常。

基本上,在我的BackgroundWorker调用的模块中,我想在主窗体上显示进度。

我该如何解决这个问题?我唯一的想法是将代码从模块移动到我的主窗体中,但这似乎是一个向后的步骤,这将涉及额外的工作。我希望有更简单的方法!

在类frmMain中调用代码:

Friend WithEvents BackgroundWorker As New System.ComponentModel.BackgroundWorker

Private Sub btnTest_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnTest.Click
    ' Specify that we do NOT want the background operation to allow cancellation
    BackgroundWorker.WorkerSupportsCancellation = False
    ' Specify that we want the background operation to report progress.
    BackgroundWorker.WorkerReportsProgress = True
    ' Start running the background operation by calling the RunWorkerAsync method.
    BackgroundWorker.RunWorkerAsync()
End Sub

Private Sub BackgroundWorker_DoWork(ByVal sender As Object, _
        ByVal e As System.ComponentModel.DoWorkEventArgs) Handles BackgroundWorker.DoWork
    Dim result As Boolean
    result = MyTest()
End Sub

Private Sub BackgroundWorker_ProgressChanged(ByVal sender As Object, ByVal e As System.ComponentModel.ProgressChangedEventArgs) Handles BackgroundWorker.ProgressChanged
    Me.Text = e.ProgressPercentage.ToString() & "%"
    sspStatus.Text = e.UserState.ToString
End Sub

Private Sub BackgroundWorker_RunWorkerCompleted(ByVal sender As Object, _
        ByVal e As System.ComponentModel.RunWorkerCompletedEventArgs) _
        Handles BackgroundWorker.RunWorkerCompleted
    If e.Cancelled = True Then
        '  The background operation was cancelled
        Me.Text = "Cancelled!"
    ElseIf e.Error IsNot Nothing Then
        '  The background operation encountered an error
        Me.Text = "Error: " & e.Error.Message
    Else
        '  The background operation completed successfully
        Me.text = "Done!"
    End If
End Sub

在单独的模块发票中生成例外的代码:

Public Function MyTest() As Boolean
    frmMain.BackgroundWorker.ReportProgress(0)
End Function

在VS 2010中使用VB.NET,使用.NET 3.5。

1 个答案:

答案 0 :(得分:0)

尝试将其设置为

Public Function MyTest(worker as BackgroundWorker) As Boolean
    worker.ReportProgress(0)
End Function

确保您正在与正确的工作人员实例交谈。

(另外:避免在实例字段中使用类名)。