If I want to periodically check if there is a cancellation request, I would use the following code below constantly inside my DoWork event handler:
    if(w.CancellationPending == true)
    {
        e.Cancel = true;
        return;
    }  
Is there a clean way for checking a cancellation request in BackgroundWorker in C# without re-typing the same code over and over again?  
Please refer to the following code below:
void worker_DoWork(object sender, DoWorkEventArgs e)
{
    ...
    BackgroundWorker w = sender as BackgroundWorker;
    if(w.CancellationPending == true)
    {
        e.Cancel = true;
        return;
    }
    some_time_consuming_task...
    if(w.CancellationPending == true)
    {
        e.Cancel = true;
        return;
    }
    another_time_consuming_task...
    if(w.CancellationPending == true)
    {
        e.Cancel = true;
        return;
    }
    ...
}
Use a while loop and delegates
Add your task in a delegate list then test your condition in a loop.
You can use Action custom delegate to make this task easier (see: http://msdn.microsoft.com/en-us/library/system.action(v=vs.110).aspx )
void worker_DoWork(object sender, DoWorkEventArgs e)
{
    List<Action> delegates = new List<Action>();
    delegates.add(some_time_consuming_task);
    delegates.add(another_time_consuming_task);
    BackgroundWorker w = sender as BackgroundWorker;    
    while(!w.CancellationPending && delegate.Count!=0)
    {
        delegates[0]();
        delegates.remove(0);
    }
    if(w.CancellationPending)
        e.Cancel = true;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With