0

I tried backgroundworker but doesnt work, as i need to update my form with each step and the backgroundworker.progresschanged only works as percentage. and if it were for only one step it could have been done with one. I also thought about making 10 different background workers and doing it that way. but then how would i cacth the exceptions and show the exceptions. and each of my try statements implements excel functions and excel workbook functions. which is also not possible in background worker.

Private Sub btnStart_Click(sender As Object, e As EventArgs) Handles   btnStart.Click

    pctrBoxStep1.Image = My.Resources.Yellow1
    lblStep1.BackColor = Color.Yellow
    workbook.Activate()
    Try
        'some stuff
    Catch ex As Exception
        int = -1
        pctrBoxStep1.Image = My.Resources.red
        lblStep1.BackColor = Color.Red
        MessageBox.Show("There was an Error!!" & Environment.NewLine & ex.Message, "Error", MessageBoxButtons.RetryCancel, MessageBoxIcon.Error)
    End Try
    'Repeat for 9 more steps

End Sub

1 Answers1

0

and each of my try statements implements excel functions and excel workbook functions. which is also not possible in background worker.

See this question. This is the only reason I can think of why you'd be having trouble using Excel functions in a BackgroundWorker.

I also thought about making 10 different background workers and doing it that way. but then how would i cacth the exceptions and show the exceptions.

From what you describe, this is probably the approach I would take. It sounds like you don't need to track the progress percentage of each worker at all. In that case, I would use the ReportProgress call only in your Catch statements. Something like:

Private Sub bgwStep1_DoWork(sender As Object, e As System.ComponentModel.DoWorkEventArgs) Handles bgwStep1.DoWork
    Try
        'some stuff
    Catch ex As Exception
        bgwStep1.ReportProgress(0)
        System.Threading.Thread.Sleep(1000) 'Precautionary
    End Try
End Sub

Private Sub bgwStep1_ProgressChanged(sender As Object, e As System.ComponentModel.ProgressChangedEventArgs) Handles bgwStep1.ProgressChanged
    int = -1
    pctrBoxStep1.Image = My.Resources.red
    lblStep1.BackColor = Color.Red
    bgwStep1.CancelAsync()
End Sub

Private Sub bgw1_RunWorkerCompleted(sender As Object, e As System.ComponentModel.RunWorkerCompletedEventArgs) Handles bgw1.RunWorkerCompleted
    bgw2.RunWorkerAsync()
End Sub

Notes:

  • Each BackgroundWorker must have its WorkerSupportsCancellation property set to True.
  • Sleep is called to make sure the UI thread has time to cancel the BackgroundWorker before it completes.
  • Keeping the data from the exception thrown is a little more complicated, but this question illustrates how to do so should you decide to go that route.
Community
  • 1
  • 1
Josh
  • 1,088
  • 1
  • 7
  • 16