Question

I know there are a lot of questions on BWs out there, but i still felt the need to ask this question/didn't feel like i got the information i wanted... or someone has to explain this to me in a way that i can understand... i see no actual purpose to calling BW.CancelAsync() other than it sets the CancellationPending flag to true...

So basically, my question is: Why call CancelAsync() on a BW?

Or the same question in a different way: my code is setup this way, is this OK or should i absolutely call CancelAsync() in there? What purpose does CancelAsync() serve that this code won't handle?

This is a bit dummed down but you get the general idea anyway.

void BW_DoWork(object sender, DoWorkEventArgs e)
{
    Process_Status LastProcessed = Process_Status.None;

    foreach(Iteration iter in Iterations)
    {
        //global form flag set when user presses CANCEL AND ROLLBACK button...
        if (!this.IsRollBack)
        {
            try
            {
                //DO SOME WORK HERE
                LastProcessed = Process_Status.SomethingSucceeded;
            }
            catch
            {
                this.LastFail = Process_Status.SomethingFailed;
                //this, for me, cancels the thread and runs RunWorkerCompleted...
                e.Cancel = true;
            }
        }
        else
        {
            this.LastFail = LastProcessed;
            //this, for me, cancels the thread and runs RunWorkerCompleted...
            e.Cancel = true;
        }
    }
}

And then in the RunWorkerCompleted...

void BW_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
    if (e.Cancelled)
    {
        switch(this.LastFail)
        {
             //DO SOMETHING MEANINGFUL HERE BASED ON GLOBAL STATUS...
        }
    }
}

Can someone help me understand the purpose of CancelAsync() better?

Was it helpful?

Solution

It is meant for a cancel button. If you click the cancel button, it call CancelAsync().

In your BackgroundWorker DoWork you scan for when E.Cancel =true. If you detect E.Cancel is true, then you stop the code inside the Background worker in a controlled way.

This allows you to cleanup what you are doing inside the BackgroundWorker instead of forcefully stopping it where it is.

You can use Global Variables to do this. CancelAsync is just a cleaner way of doing it.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top