3

I have the following implementation. I was getting an timeout exception after 100 seconds. And I have added 10 minutes to httpclient as follows, but I am still getting the same error message.

using (var httpClient = new HttpClient(new HttpClientHandler()))
{
   httpClient.Timeout = TimeSpan.FromMinutes(10);
   var request = new HttpRequestMessage(method, requestUri);
   if (body != string.Empty)
   {
      request.Content = new StringContent(body, Encoding.UTF8, "application/json");
    }

    try
    {
       using (var response = httpClient.SendAsync(request).Result)
       {

       }
       catch (Exception ex)
       {

       }
     }
 }
casillas
  • 16,351
  • 19
  • 115
  • 215
  • 4
    You need to read [You're Using HttpClient Wrong and It's Destabilizing Your Software](https://aspnetmonsters.com/2016/08/2016-08-27-httpclientwrong/). I recommend using [Flurl.Http](https://tmenier.github.io/Flurl/) which solves these problems for you. – mason Jan 12 '18 at 16:45
  • 3
    You're also using async wrong. Don't access the .Result property. You need to await the response of the call. – mason Jan 12 '18 at 16:46
  • @mason, how should I update my code then? I mimicked the following sof answer https://stackoverflow.com/questions/41762947/how-to-get-and-print-response-from-httpclient-sendasync-call. – casillas Jan 12 '18 at 16:59
  • That answer is terrible. I've already told you how to improve your code. Switch libraries, and use `await` instead of accessing the `.Result` property of the task. – mason Jan 12 '18 at 18:05
  • @mason I cannot change the libraries at the moment, but I can migrate it at the end of the month. `SendAsync` by itself is not an await?? – casillas Jan 12 '18 at 18:07
  • No. Sounds like you need to do some basic research on how async/await should be integrated. It's a complicated subject. But just for a quick primer, you should read over [Async/Await - Best Practices in Asynchronous Programming](https://msdn.microsoft.com/en-us/magazine/jj991977.aspx). A proper async call would look like `await httpClient.SendAsync(request);` – mason Jan 12 '18 at 18:11
  • Why can't you change libraries right now? What is preventing you from using the best tool for the job? – mason Jan 12 '18 at 18:12
  • Looks like a single HttpRequest, why not use WebClient? – Hozikimaru Jan 12 '18 at 18:33

0 Answers0