beluchin
beluchin

Reputation: 12682

How to cancel a long-running operation that can be cancelled at many points?

We have a long-running operation comprised of many points at which it can be cancelled. If we were to use the task cancellation token approach, we would need to make sure that we check for cancellation at every required place.

This seems suboptimal to us. We see two problems here:

  1. we need to make a cancellation token check at every place where there is opportunity for cancellation which we feel clutters the code and there is a potential to miss points in the code at which there are other opportunities for cancellation.
  2. if we follow the guideline to avoid global variables, we need to pass the cancellation token as a parameter to many methods which we feel is repetitive and clutters the code.

Should we use a global cancellation token to deal with 2.? Should we use AppDomain to deal with 1. and 2.?

Upvotes: 4

Views: 196

Answers (1)

Reed Copsey
Reed Copsey

Reputation: 564333

we would need to make sure that we check for cancellation at every required place.

This is really the proper way to handle this.

A global token doesn't solve checking at each required place, and would only potentially help with not passing around tokens as parameters to the methods. It does limit you - if you use a global token, you take away the ability to now, or in the future, modify your routine to have multiple operations in flight with separate cancellation.

However, I would argue that passing the token around is actually a good thing. This makes your API self-documenting - each method which accepts a token is something which may, potentially, raise a OperationCanceledException and supports cancellation.

Any other approach that avoids these issues is going to require a model for cancellation that is not cooperative. This has detrimental side effects, as forcibly "killing" running operations is rarely a good thing (for example, there are many reasons to avoid Thread.Abort that are easy to find).

Upvotes: 5

Related Questions