3

I'm using Microsoft Solver Foundation in my recent WinForms project to solve a scheduling problem.

My scheduling method is 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 scheduling process takes long time(ScheduleUsingMSF() method that I don't have any control on it, take long time), I used a BackgroundWorker to call my scheduling method to prevent GUI freezing.

When a scheduling process take long time users may wants to cancel current scheduling operation and change their parameters and run it again, so I want to provide a cancellation mechanism to them, so I used following code to cancel operation according to How to: Use a Background Worker:

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 should I check if ((bw.CancellationPending == true)) to cancel Schedule() method?

Masoud
  • 8,020
  • 12
  • 62
  • 123
  • There's a dirty hack posted in this dupe link: [How to “kill” background worker completely?](http://stackoverflow.com/questions/800767/how-to-kill-background-worker-completely) – Bjørn-Roger Kringsjå Jul 12 '15 at 10:55
  • 1
    Well, that cannot work of course. If you can't break into that black box then you have no way to fix this. Use a telephone, talk about ISolverParameters.QueryAbort – Hans Passant Jul 12 '15 at 13:05
  • @HansPassant: thanks, I searched about `ISolverParameters.QueryAbort` but doesn't found any useful things, do you have any sample or something else about `ISolverParameters.QueryAbort`? – Masoud Jul 13 '15 at 03:25

1 Answers1

0

CancellationPending property should be checked by background process. If that property is set to true then your background worker should stop its job, free resources, do final stuff, etc. But since you don't have control over ScheduleUsingMSF(); you want be able to benefit from it.

serhiyb
  • 4,753
  • 2
  • 15
  • 24