Search code examples
vb.netuser-interfacebackgroundworker

How to pass text parameter to ProgressChanged?


I'm a VB.Net newbie, and need to write a long-running process with a While/End While loop.

To avoid freezing the UI, I added a BackgroundWorker object on the form.

Next, I needed to update the UI, but found that the thread cannot do this. Instead, the thread must call ReportProgress() to trigger the ProgressChanged() event.

However, I need to pass the text from the exception (ex.Message) to the event, but didn't find an example on how to do this. I need that text message to update the form's title bar.

Here's the code:

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

Thank you.


Edit: Here's how to get the pass the error message to the event, and change the form's title text:

        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

Solution

  • The Reportprogress method has an overload that takes a Int32 and an Object parameter. You can pass the message or the complete Exception to the main Thread.

    In the ProgressChanged event you can retrieve it from the UserState property.