Canceling a background worker

I am using Microsoft Solver Foundation

in my recent project WinForms

to solve a scheduling problem.

My scheduling method looks something like this:

public class Scheduler
{
    public void Schedule()
    {
        InitializeParameters();
        PrepareDateFromDatabase();
        ScheduleUsingMSF(); //<---- this line is black box and take a long time to execute
        SaveSchedulingResultToDb();
    }
}

      

Sometimes the scheduling process takes a long time (the ScheduleUsingMSF () method, which I have no control over it , takes a long time), I used BackgroundWorker

to call my scheduling method to prevent GUI freeze.

When the scheduling process takes a long time, users can abandon the current scheduling work and change their settings and start it again, so I want to provide them with an undo mechanism, so I used the following code to undo the operation according to How to use the background desktop :

bw.WorkerSupportsCancellation = true;
...
private void bw_DoWork(object sender, DoWorkEventArgs e)
{
    var scheduler = new Scheduler();
    scheduler.Schedule();
}
private void buttonCancel_Click(object sender, RoutedEventArgs e)
{
    if (bw.WorkerSupportsCancellation == true)
    {
        bw.CancelAsync();
    }
}

      

Where and how can I check if ((bw.CancellationPending == true))

for method cancellation Schedule()

?

+3


source to share


1 answer


Property

Cancel> must be checked by a background process. If this property is set to true, your background worker should terminate, free resources, render final stuff, etc. But since you have no control over ScheduleUsingMSF (); you want to be able to benefit from it.



0


source







All Articles