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
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)?
Not sure why this hasn't been answered but my view is that all Async methods should take a CancellationToken
parameter. Even if the method does not do anything "heavy", it needs to take this so that it can pass the token down to other Async calls that it makes.
So even if the method doesn't directly use the token, it has no way of knowing how it might be used by another async method further down the chain.
So, as the person defining the interface, you should specify the CancellationToken
on every async method. It's down to the implementer of the method whether they think they need their method to use it directly or not but everyone shoudl be cascading this down.
As Jeroen already mentioned, it costs practically nothing to pass this token down without directly using it.