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?
Asked
Active
Viewed 789 times
2
-
When you say 'I want to check for an error myself', do you mean you want the BackgroundWorker thread to check for the error itself? And cancel the background task if there is an error? – Paul Ruane Mar 16 '10 at 13:57
-
No, say for instance that there is information missing in the database that is required to complete the steps. It wouldn't throw an error, but it is something that could cause problems if allowed to continue. – Mike Wills Mar 16 '10 at 14:14
1 Answers
5
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 Rosendo
- 25,001
- 7
- 80
- 118
-
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 Mar 16 '10 at 14:25
-
2In addition, DoWork should set Args.Canceled=true to pass the Cancel status on to the Completed event. – H H Mar 16 '10 at 14:51
-
Shouldn't that be bgWrk.CancelAsync()? I don't have a bgWrk.Cancel in .NET 3.5 – Mike Wills Mar 16 '10 at 15:16
-
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 Rosendo Mar 16 '10 at 15:38