Under what circumstances does Async support cancellation

I am currently building an async version of an existing API and I am struggling to find any guidance on when it is a good idea to support cancellation. Some Async methods in BCL do not have an overload that accepts CancellationToken

, and I found this MSDN article that says

no cancellation support is required for all asynchronous methods

So what are the conditions to support cancellation with help CancellationToken

?

I'm leaning towards the following conditions:

  • Any expected method called also supports cancellation
  • Any method expected may take longer than n ms to complete
  • Method implementation has one or more logical exit points (for example, no side effects of delaying exit)

Are these reasonable terms? are there others?

+3


source to share


1 answer


This is just my opinion, but I would say that if the methods async

you call all support invalidation, then yours should. In a similar vein, if you are building an API await

in a naturally asynchronous operation, do your best to support cancellation (eg via CancellationToken.Register

).

I would also say that any (synchronous) cpu binding method that can take a "long time" should periodically register an undo token ( CancellationToken.ThrowIfCancellationRequested

). "Long time" is relative, but as a rough guideline I would say something over half a second (on older hardware, not our 8 core dev machines;).



In any other scenario, you're talking about a much less useful form of cancellation - in particular, cancellations can take an arbitrary amount of time to take effect. For example, if some methods async

support it and others don't. I'm not sure how useful the cancellation token option is in this case; you might want to insert it, but be sure to document its limitations.

+6


source







All Articles