Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a clean way for checking a cancellation request in BackgroundWorker without re-typing the same code over and over again?

Tags:

c#

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;
    }

    ...
}
like image 314
devpro101 Avatar asked Oct 29 '14 12:10

devpro101


1 Answers

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;
}
like image 68
Ludovic Feltz Avatar answered Nov 02 '22 05:11

Ludovic Feltz