BackgroundWorker - When to check CancellationPending

BackgroundWorker was introduced in .NET 2.0 to solve the problem of executing long-running tasks while maintaining an interactive user interface.

One of the key issues that arises when using BackgroundWorker is determining when to check if the user has cancelled the long running operation. Thanks to this higher level abstraction (BackgroundWorker) a few insights become clear:
  • Cancellation must occur at some stopping point in the long running algorithm. By "stopping point" I mean some step in the process where you can check if the user has requested cancellation.
  • Check for cancellation only as frequently as is necessary to maintain the sense of interactivity.

The key insight, however, regards choosing the point at which you check for cancellation.

  • Check for cancellation just before executing a unit of work.

If you are executing the last unit of work then, essentially, there is no way to cancel the long running operation; the moment has passed. Since the user won't have to wait much longer until the operation is complete this does not conflict with the goal of supporting interactivity.

An analogy for the unit of work is jumping across stones to cross a creek. You can decide to stop at any time before you make the jump. You can decide to stop on any stone along the way. But you can't stop a jump while you're in the air (no jetpacks!) and you can't back out once you've jumped the last stone!

No comments:

Post a Comment