2

I am getting "A task is cancelled" issue intermittently at line "resp = client.GetAsync(relativeUri);". Code Snippet below.

    using (var client = new HttpClient())
    {
         client.DefaultRequestHeaders.Add("Authorization", "Bearer " + JwtAccessToken);
         client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue(accept));
         resp = client.GetAsync(relativeUri);
    }
General Grievance
  • 4,259
  • 21
  • 28
  • 43
Rakesh
  • 21
  • 2
  • The connection timed out -- it's confusing. See e.g. https://stackoverflow.com/questions/29179848/httpclient-a-task-was-cancelled. – canton7 Sep 24 '21 at 10:14
  • 2
    In more recent .NET versions, the `OperationCanceledException` has an InnerException of `TimeoutException`, see https://github.com/dotnet/runtime/issues/21965 – canton7 Sep 24 '21 at 10:19

1 Answers1

1

Usually it means that the request was cancelled by timeout

By the way you forgot to await your async Get call in this snippet

HaroldMorgan
  • 164
  • 6
  • Even i add async before Get, that is of no use. – Rakesh Sep 24 '21 at 10:23
  • Does it would be a good idea to add "client.Timeout = TimeSpan.FromMinutes(30);" this code? Because it seems working when i have added this code. – Rakesh Sep 24 '21 at 10:24
  • 2
    @Rakesh First, understand what a timeout is, and when it can occur. Second, work out what timeout you want: how long do you want to wait for the server to respond before giving up? You could be waiting forever! Third, figure out what you're going to do if a timeout happens. – canton7 Sep 24 '21 at 10:51