0

I am using GetAsync method to retrieve the response from the server. The following code runs fine for the first two iterations and then errors out with the message "A task was canceled". I searched online but didn't find any workaround. There was a recommendation to use async/await due to deadlock, but I don't think that's the issue here, and also it didn't work.

Any ideas what is causing the exceptions and how to prevent it?

Edit: I have already gone through this question, and tried using async/await as mentioned and changed the default timeout to 5 minutes instead of 100 seconds. Neither of them worked. My guess is it's something else as from the Netstat log, I see the port to be in TIME_WAITING state.

HttpClient - A task was cancelled?

Note:I am using System.Net.Http 4.3.4 version and .NET 4.6.1.

using System;
using System.Net.Http;

namespace Main
{
    class Program
    {
        static void Main(string[] args)
        {
            var client = new HttpClient();
            string url = "https://www.google.com";
            for (int i = 0; i < 10; i++)
            {
                var response = client.GetAsync(url, HttpCompletionOption.ResponseHeadersRead).GetAwaiter().GetResult();
                Console.WriteLine(response.StatusCode);
            }

            Console.ReadKey();
        }


    } 
}
  • This code actually works perfectly fine on my machine and it returns OK for all ten responses. If I were you I would try a different web server or a different IP address and see if that yields any different results. – CyanCoding May 29 '20 at 17:06
  • Also take a look at [HttpClient - A task was cancelled?](https://stackoverflow.com/questions/29179848/httpclient-a-task-was-cancelled). – CyanCoding May 29 '20 at 17:08
  • @CyanCoding, did you run the code with the HttpClient v4.3.4. Because I tried out with different server also, but every time I am getting the same response, (i.e. only 2 successful calls out of 10). The netstat log showed the port in Time_waiting state for me – Divyansh Chowdhary May 29 '20 at 17:09
  • I have already gone through that link, but that didn't provide me the correct explanation about the exception, I am getting. Because I don't think reading the response from google server would take more than 100 seconds. Also, I tried increasing the timeout to 5 minutes, but that didn't help either. – Divyansh Chowdhary May 29 '20 at 17:11
  • Make Main() `async` and `await [HttpClient].GetAsync(...)`. Use a `static` HttpClient. – Jimi May 29 '20 at 17:21
  • @Jimi, As mentioned already, I have already tried making main as async and using await while making the request. Static Httpclient would not make a difference here, as I am initializing the client only once in the Main – Divyansh Chowdhary May 29 '20 at 17:26
  • I don't see any code that reflects your description. HttpClient is meant to be used that way, so use it that way. – Jimi May 29 '20 at 17:27
  • @Jimi [code with async/await](https://pastebin.com/y6VvqXX3), here is the code that I tried with async/await with static client, and it produced the same error. – Divyansh Chowdhary May 29 '20 at 17:39
  • You can do it either way, it would work either way. The aysnc way is preferable. Mandatory in some contexts. You have to note that `response` is disposable, so write something like: `using (var response = client.GetAsync(url, HttpCompletionOption.ResponseHeadersRead).GetAwaiter().GetResult()) { Console.WriteLine(response.StatusCode); }`. Use a static HttpClient. – Jimi May 29 '20 at 17:41
  • @Jimi, thanks. Making the response as disposable works fine. Can you please provide me, the explanation regarding why it works when used inside the using block, versus when creating a new response every time, as shared in the above code. I am not able to understand the difference b/w two. I understand that while declaring it in a using block, it would be automatically marked for dispose by GC after its execution. But why does it result to "Task was cancelled" error, when not used inside a using block. – Divyansh Chowdhary May 29 '20 at 17:50
  • Sorry, but explaining in comments how the ServicePointManager handles ServicePoints and the Connection Pool, intermixed with blocking async calls, HttpClient functionality and disposable objects is a little too much. Btw, the GC is irrelevant here, it doesn't have time to do anything here. – Jimi May 29 '20 at 17:57
  • Ok, No problem. Thanks for the help @Jimi – Divyansh Chowdhary May 29 '20 at 18:03

0 Answers0