© 2026 Hedgehog Software, LLC

TwitterGitHubDiscord
More
CommunitiesDocsAboutTermsPrivacy
Search
Star
Setup for Free
C#C
C#•3y ago•
27 replies
MetalPuppyTheThird

❔ HttpClient does not respect CancellationToken

App & Deployment Details
Applications X and Y are DotnetCore 6.0 applications.
X runs on K8s and Y on VMs on the cloud.

Context of the problem
I have two applications, X and Y. Y is a dumb app and it's job is to fetch data from various datasources. Y has certain REST styled endpoints. X has a logic to call the said endpoints of application Y. All calls are async and the use case needs the Http Post call to adhere to the cancellationToken.

Problem
The cancellationToken is set in this fashion
using var cts = CancellationTokenSource.CreateLinkedTokenSource(token);
  cts.CancelAfter(certainValue);
using var cts = CancellationTokenSource.CreateLinkedTokenSource(token);
  cts.CancelAfter(certainValue);


and used in the following manner
response = await _client.SendAsync(request, cancellationToken);
response = await _client.SendAsync(request, cancellationToken);


we also have logging on top of the httpClient call and it looks like so
var stopWatch = Stopwatch.StartNew();
try
{
  response = await PostAsync(request, cancellationToken);
}
catch
{
  ElapsedTime = stopWatch.ElapsedInMilliseconds();
}
var stopWatch = Stopwatch.StartNew();
try
{
  response = await PostAsync(request, cancellationToken);
}
catch
{
  ElapsedTime = stopWatch.ElapsedInMilliseconds();
}


Observations
1. The CancellationToken value is always set to 20s. From the ElapsedTime that is logged, we observed that the call does not timeout ~20s but in 1/10th of cases is >20s and has no pattern
2. The 20s timeout was changed to 30s and similar behaviour was observed.
3. Found this SO article describing the same problem

Solutions Tried
1. Used the Polly.Timout but still observing the same issue
Stack Overflow
HttpClient cancellation doesn't kill underlying TCP call
I'm trying to set a default timeout for my HttpClient calls to 5 seconds.

I've done this via CancellationTokenSource.

Here's the pertinent bit of code:

var cancellationToken = new
HttpClient cancellation doesn't kill underlying TCP call
GitHub
Timeout
Polly is a .NET resilience and transient-fault-handling library that allows developers to express policies such as Retry, Circuit Breaker, Timeout, Bulkhead Isolation, and Fallback in a fluent and ...
Timeout
C# banner
C#Join
We are a programming server aimed at coders discussing everything related to C# (CSharp) and .NET.
61,871Members
Resources
Was this page helpful?

Similar Threads

Recent Announcements

Similar Threads

CancellationToken not cancelling
C#CC# / help
15mo ago
HttpClient does not return anything
C#CC# / help
3y ago
Queue Cancellationtoken
C#CC# / help
2y ago
✅ Downloading file with HttpClient does not work
C#CC# / help
14mo ago