Search code examples
c#backgroundworkerrequest-cancelling

Canceling BackgroundWorker within the Thread


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?


Solution

  • 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.