Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to detect if HttpClient.CancelPendingRequests was used to cancel pending requests?

Application Setup


  1. I am using HttpClient to make mulitple Async POST requests to a REST service from a Windows Forms Application.
  2. Meanwhile the response is fetched from the REST service the application shows a Processing... window with a Cancel button.
  3. Now, when the user presses the Cancel button I am using HttpClient.CancelPendingRequests to cancel the ongoing requests.
  4. Using HttpClient.CancelPendingRequests throws TaskCanceledException on the PostAsync mthod call.

Query

  1. Is there any way I detect that the TaskCanceledException was thrown due the calling of HttpClient.CancelPendingRequests and not due to any other reason (like timeout)
  2. Is there any other approach to achieve similar cancellation functionality?

Thanks


like image 655
Rahul Avatar asked Dec 05 '25 05:12

Rahul


1 Answers

Catch the exception and check the TaskCanceledException.CancellationToken.IsCancellationRequested property. If true, you can be fairly certain that it was an explicitly requested cancellation vs. a timeout.

Having said that, be cautious with this solution and do some testing. As I discovered a while back, there are cases where you would think that bit should be set and it is not.

like image 127
Todd Menier Avatar answered Dec 07 '25 19:12

Todd Menier



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!