0

This is how I set up my Background Worker

The question is: How do I terminate the process midway? I have to create a cancel button that will stop current processing.

I thought of use the line below...

if ((worker.CancellationPending == true))
                {
                    e.Cancel = true;
                }

...and encapsulating the AllocateTrades2 method inside, but that would mean I have to call the Cancel Flag from somewhere else, and it will check it only after the method is done processing.

And I can't just "pretend" that it is not doing anything because if the user clicks the same operation again, an exception will be thrown that the worker is in use.

An example of what I want to do:

public void bw_DoWork(object sender, DoWorkEventArgs e)
{
    AllocateTrades2();
}
public void AllocateTrades()
{
    Method1();
    CheckTerminate();

    Method2();
    CheckTerminate();

    //Click the cancel button in the UI during method 3 processing
    Method3();
    CheckTerminate();
}

And the CheckTerminate() stops all of its processing and makes itself available for future calls. Is what I'm trying to do possible?

Community
  • 1
  • 1
Alexey
  • 3,607
  • 8
  • 34
  • 54

2 Answers2

3

You'd have to do something like...

public void AllocateTrades()
{
    if (!worker.CancellationPending)
    {
        Method1();
    }

    if (!worker.CancellationPending)
    {
        Method2();
    }

    if (!worker.CancellationPending)
    {
        Method3();
    }
}

.Net cannot decide for you what is an "atomic" operation with respect to your background work, so you must decide how often and where to check for a pending cancellation.

Idle_Mind
  • 38,363
  • 3
  • 29
  • 40
  • It might be an overkill (depending on the size of the project and number of places where this is checked) but this looks like boilerplate and repeating code and I would create an aspect and move the check for pending cancellation in it. – Karel Frajták May 22 '13 at 16:13
  • 1
    Didn't exactly do the same structure, but the idea of checking for every method was the same. +1 and accepted. – Alexey May 22 '13 at 16:36
0

The answer is YES.

Wherever you check for 'CancellationPending', you can stop your worker.

In your example you have these options:

  • check in the 'AllocateTrades2()'-Function itself

     If (bw.CancellationPending) {
        e.Cancel = True
        return; }
    

Note: If you check it here, you can cancel the process 'midway'.

  • check from outside, before you run your next process

     If (!worker.CancellationPending) {
        MethodX(); }
    

Generally, you should check for CancellationPending wherever it makes sense (e.g. in a loop: after or before an item has been processed).

Fabian Bigler
  • 10,403
  • 6
  • 47
  • 70