Differentiate time exceeded from no server response using HttpClient

Viewed 344

Is there a way, using HttpClient, to differentiate a time-out "when we get no response from the server" from a "time exceeded" operation?

Let me explain our issue:

  • Case1: If we don't get any response from the server in 10 seconds then this is an issue.
  • Case2: If we get a response from the server, but the server continues to transfer data and it takes a while, maybe 30 seconds or more. Then this is not an issue.

Is there a way using .NET HttpClient class to handle this scenario? From what I tested specifying a TimeOut on HttpClient will put the same time-out for case1 and case2.

2 Answers

You can use one of the variants of the various methods that accepts a CancellationToken.

If the cancel happens after the method's Task has completed, the cancellation is ignored and you can continue with e.g. processing the content from the result.

var client = new HttpClient();
var cancel = new CancellationTokenSource();
cancel.CancelAfter(TimeSpan.FromSeconds(10));
var resp = client.GetAsync("http://www.google.co.uk", cancel.Token).Result;

So, in the above, provided we get enough back from the server for the GetAsync to complete, the cancellation has no effect.

Related