开发者

Canceling BackgroundWorker within the Thread

开发者 https://www.devze.com 2022-12-23 05:55 出处:网络
I have a longer running multi-step process using BackgroundWorker开发者_Python百科 and C#. I need to be sure that each step is completed successfully before moving on to the next step. I have seen man

I have a longer running multi-step process using BackgroundWorker开发者_Python百科 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?


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号