I've started using System.Net.Http.HttpClient and it's a great class. I'm at a point where I want to give my program's user the ability to cancel operations, for example if a bunch of HTTP requests take too long to complete. So, naturally, I've come across the CancellationTokenSource class and modified my calls to the async methods of HttpClient to also pass them a CancellationToken. In my UI code I can now "cancel that token", and indeed it interrupts whatever HTTP request was in progress at that point.
What I didn't expect, however, is that this causes the interrupted method to throw the TaskCanceledException exception.
Here's my question : I've looked at the MSDN documentation for HttpClient and I have found no mention of that exception. I suppose that is because it's a common behavior to any async method that takes a CancellationToken, but so far I haven't found much information about that. Can you confirm or infirm my supposition, and point me to the relevant documentation ?
My "real question" is whether I'm using the CancellationToken mechanism right, meaning, is that exception supposed to happen, or am I doing something wrong ?
If that exception is supposed to happen, and if it is a mechanism I can rely on, then it will simplify my code. Right now, I test my token's IsCancellationRequested property after each call to HttpClient async methods to determine if my methods should proceed or return, but with this exception, all that additional code becomes pointless.
I'm cancelling the token using this statement :
myCancellationTokenSource.Cancel();