Conditionally run a backgroundworker RRS feed

  • Question

  • I am trying to run a backgroundworker, but only when a certain radiobutton is checked . if it is unchecked then i want to cancel the backgroundworker - the moment when its checkstate changes.

    I have tried including the chackstate as an argument of the backgroundworker runworkerAsync call and the put the code in an if statement but itlooks like the thread does not know that the checkstate has changed

      Private Sub OptionUpdate_CheckedChanged(sender As Object, e As EventArgs) Handles OptionUpdate.CheckedChanged
            If OptionUpdate.Checked = True Then
            End If
        End Sub

    This is the code for my backgroundworker DoWork method

     Private Sub BackgroundWorker1_DoWork(sender As Object, e As DoWorkEventArgs) Handles BackgroundWorker1.DoWork
            Dim myOptionUpdateState As Boolean
            myOptionUpdateState = e.Argument
            If BackgroundWorker1.IsBusy Then
                If BackgroundWorker1.WorkerSupportsCancellation Then
                End If
            End If
            If myOptionUpdateState = True Then
                SetControlTextProperty_ThreadSafe(RadLabel1, "")
                Dim myString As String
                myString = "Please enter the Fuel charge Rate to update rates..."
                For i As Integer = 0 To myString.Length
                    If myOptionUpdateState = False Then
                    End If
                    SetControlTextProperty_ThreadSafe(RadLabel1, myString.Substring(0, i))
                    If i = myString.Length Then
                        i = 0
                    End If
            End If
        End Sub

    How can I make it that when the checkstate changes then the background worker will stop

    If you think it you can achieve it

    Friday, February 20, 2015 8:44 AM


  • If you want to cancel the Background worker when the RadioButton in unchecked, then put the BackGroundWorker1.CancelAsync call in the CheckChanged event handler for the RadioButton

    Private Sub RadioButton1_CheckedChanged(sender As Object, e As EventArgs) Handles RadioButton1.CheckedChanged
        If Not RadioButton1.Checked Then BackgroundWorker1.CancelAsync
    End Sub

    Inside the loop in the BackgroundWorker's DoWork method, you check to see if you are supposed to cancel like this

    For i As Integer = 0 To myString.Length
        If BackgroundWorker1.CancellationPending Then
            e.Cancel = True 
            Exit For 
        End If
        'your work goes here

    • Proposed as answer by MDeero Friday, February 20, 2015 12:13 PM
    • Marked as answer by Youjun Tang Friday, February 27, 2015 8:52 AM
    Friday, February 20, 2015 11:37 AM