I have a longer running multi-step process using BackgroundWorker and C#. I need to be sure that each step is completed successfully before moving on to the next step. I have seen many references to letting the BackgroundWorker catch errors and canceling from clicking on a Cancel button, but I want to check for an error myself and then gracefully end the process. Do I treat it just like someone clicked the cancel button, or is there another way?
+5
A:
Given a BackgroundWorker
bgWrk:
You can set bgWrk.Cancel = true;
when an error occurs. Doing this has the following effects:
This then switches the CancellationPending
flag to true which you can periodically check the background worker for, and then cancel appropriately. That would be considered the "best practice" of doing it as far as I know.
You can then make sure no more of your code runs if the CancellationPending
flag is set, and basically waits to be cancelled from the caller. It should work gracefully for you.
Kyle Rozendo
2010-03-16 13:57:35
+1 Nice smooth solution! This gives good ideas. Thanks! =)
Will Marcouiller
2010-03-16 14:08:22
Thank you for confirming what I assumed needed to be done. I just didn't want to make that assumption without seeing if there was a different (or better) way.
Mike Wills
2010-03-16 14:25:15
In addition, DoWork should set Args.Canceled=true to pass the Cancel status on to the Completed event.
Henk Holterman
2010-03-16 14:51:13
Shouldn't that be bgWrk.CancelAsync()? I don't have a bgWrk.Cancel in .NET 3.5
Mike Wills
2010-03-16 15:16:14
The Cancel is held by the DoWork event, the CancelAsync() is via the object (which is doing the monitoring to perform the cancel itself) (And +1 @Henk)
Kyle Rozendo
2010-03-16 15:38:36