16

How to set Timeout property to Windows.Web.Http.HttpClient operation. The code sample I used is below.

public HttpClient httpClient;
public CancellationTokenSource cts;

public void SendRequest(addressUri,postrequestbody)
{
    HttpHelper.CreateHttpClient(ref httpClient);
    cts = new CancellationTokenSource();
    HttpRequestMessage msg = 
        new HttpRequestMessage(new HttpMethod("POST"), 
                               new Uri(addressUri));
    msg.Content = new HttpStringContent(postrequestbody);
    msg.Content.Headers.ContentType = 
        new HttpMediaTypeHeaderValue("application/json");
    HttpResponseMessage response = 
        await httpClient.SendRequestAsync(msg).AsTask();

    if (response.StatusCode == HttpStatusCode.Ok)
    {
    }
}
David Sherret
  • 101,669
  • 28
  • 188
  • 178
asitis
  • 3,023
  • 1
  • 31
  • 55

1 Answers1

23

Use a CancellationToken:

try 
{
    CancellationTokenSource cts = new CancellationTokenSource(2000); // 2 seconds
    HttpClient client = new HttpClient();
    HttpResponseMessage response = await
        client.SendRequestAsync(request).AsTask(cts.Token);
}
catch (TaskCanceledException ex)
{
    // Catch operation aborted ...
}
kiewic
  • 15,852
  • 13
  • 78
  • 101
  • Have you tried a timeout > 60 seconds? (your example uses 2 seconds) I tried setting 10 minutes like so..... var response = await httpClient.PutAsync(operation, payload, new CancellationTokenSource(600000).Token); But this returns 404 NOT FOUND after 60 seconds still. – iupchris10 Sep 10 '15 at 15:22
  • 1
    @iupchris10 I know it's like 2 years too late, but 60 seconds is less than 10 minutes. If you have a response code (i.e. the server has _responded_) then your request hasn't timed out. I would _expect_ this behaviour since it's the correct behaviour. The code above will cancel your request after 10 minutes IF there is no response / the response takes too long. That's not the case in your example. – ProgrammingLlama Oct 11 '17 at 06:35
  • 1
    I know this is 3 years later but it's 600,000 not 60,000, which is 10 minutes – geedubb Oct 16 '20 at 15:22