如何传递文本参数给ProgressChanged



我是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

Reportprogress方法有一个重载,它接受一个Int32 一个Object参数。您可以将消息或完整的Exception传递给主线程。

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

相关内容

  • 没有找到相关文章

最新更新