When should I add a CancellationToken to an async interface method?

Viewed 577

I am writing a C# interface which will have several different implementations, some of which I don't control. Given my problem domain, all (most of) the method implementations are going to involve some kind of network communication. For this reason, I am writing the interface so that all methods return instances of Task and can be run asynchronously. So far so good.

Now I am considering adding a CancellationToken parameter to some/all of the interface methods. AFAIK one should add a CancellationToken to a method when

  • the method can take a long time, and
  • there are points where the implementation can check the token and prevent further use of resources if the operation has been cancelled.

But it is not really clear to me what the criteria are when the method implementation is not known, e.g. when writing an interface. For example, some of the methods in my interface involve simple operations and are probably going to be fast enough not to need cancellation support in most cases, but I can't know for sure because I don't control all implementations, and in any case they will involve network communication so that will ultimately depend on network latency.

What are the rules of thumb/best practices to decide whether to add or not a CancellationToken to an interface method (whose implementation is unknown)?

0 Answers
Related