Reputation: 3
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();
}
}
}
Upvotes: 0
Views: 399