I used BackgroundWorker to solve a problem in my winforms application, I wanted to be able to cancel a long-running operation and see results live in ListBox while executing the operation. It works fine except when I want to add a checkbox with additional condition.
The problem is when I want to run several operation at once. Ex. both XX and YY executing XX first and then start with YY in that order.
Private Sub UpdateDB_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnTestAll.Click
If cbxTestYY.Checked OrElse cbxTesteXX.Checked Then
SetBusyState(True)
If cbxTestXX.Checked Then
bkWorker.RunWorkerAsync(1)
End If
If cbxTesteYY.Checked Then
bkWorker.RunWorkerAsync(2)
End If
End If
End Sub
Private Sub bkWorker_DoWork(ByVal sender As System.Object, ByVal e As System.ComponentModel.DoWorkEventArgs) Handles bkWorker.DoWork
If bkWorker.CancellationPending Then
e.Cancel = True
Exit Sub
Else
If e.Argument = 1 Then
AddItemToListBox("", "XX")
TestUnits(_XXDimensionUnits, True)
AddItemToListBox(" Calculating Units ")
TestUnits(_XXCalculationUnits, False)
End If
If e.Argument = 2 Then
AddItemToListBox("", "YY")
TestUnits(_YYCalculationUnits, False)
End If
End If
End Sub
I know I am trying to run multiple tasks on same backgroundworker which is not allowed, but I dont have any idea how to solve this so it runs in specific order.
Appriciate all help !!
Just tell the worker what tests it needs to perform. Start this with an enumeration that declares the tests:
And start the tests like this:
And adjust the code in the worker to test the passed argument for each test: