如何将文本参数传递给ProgressChanged?

时间:2011-07-31 07:32:49

标签: vb.net user-interface backgroundworker

我是VB.Net的新手,需要使用While / End While循环编写一个长时间运行的进程。

为避免冻结UI,我在表单上添加了BackgroundWorker对象。

接下来,我需要更新UI,但发现线程无法执行此操作。相反,线程必须调用ReportProgress()来触发ProgressChanged()事件。

但是,我需要将异常(ex.Message)中的文本传递给事件,但是没有找到有关如何执行此操作的示例。我需要该短信来更新表单的标题栏。

以下是代码:

Private Sub BackgroundWorker1_DoWork(ByVal sender As System.Object, ByVal e As System.ComponentModel.DoWorkEventArgs) Handles BackgroundWorker1.DoWork
    While (True)
        Try
            ...
        Catch ex As Exception
            'Cross-thread operation not valid: Control 'Form1' accessed from a thread other than the thread it was created on.
            'Me.Text = ex.Message

            BackgroundWorker1.ReportProgress(100)
        End Try

        System.Threading.Thread.Sleep(2000)
    End While
End Sub

Private Sub BackgroundWorker1_ProgressChanged(ByVal sender As System.Object, ByVal e As System.ComponentModel.ProgressChangedEventArgs) Handles BackgroundWorker1.ProgressChanged

        'How to get ex.Message, and change the form's title bar accordingly?
        'Me.Text = ???
End Sub

谢谢。


编辑:以下是如何将错误消息传递给事件,并更改表单的标题文本:

        Catch ex As Exception
            BackgroundWorker1.ReportProgress(100, ex.Message)
        End Try

        System.Threading.Thread.Sleep(2000)
    End While
End Sub

Private Sub BackgroundWorker1_ProgressChanged(ByVal sender As System.Object, ByVal e As System.ComponentModel.ProgressChangedEventArgs) Handles BackgroundWorker1.ProgressChanged
    Me.Text = e.UserState.ToString
End Sub

1 个答案:

答案 0 :(得分:4)

Reportprogress方法有an overload,它使Int32 成为Object参数。您可以将消息或完整的异常传递给主线程。

在ProgressChanged事件中,您可以从UserState属性中检索它。