Getting 'A task was canceled' after a few requests to the ASP.NET Web API

AlinMaiorAlinMaior USMember ✭✭

So, I'm building a Xamarin.Forms app and I made a little helper function for my requests to my Web API
public async static Task MakeGetRequest(string parameters, string url = null, bool hasISBN = false)
{
if(Bearer == null)
{
//bearer = await GetAuthToken();
}
using (var client = new HttpClient())
{
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", Bearer);

            var response = await client.GetAsync(string.Format("{0}/{1}", string.IsNullOrEmpty(url) ? baseUrl : url, parameters));

            var responseString = await response.Content.ReadAsStringAsync();

            return JsonConvert.DeserializeObject<ResponseType>(responseString);
        }
    }

All the calls to the API are awaited, and I'm making the calls using the IP, not to localhost.
But after a few requests, I'm starting to get the error "A task was canceled" on API calls.
If I deploy the API to Azure and make the calls there I'm not getting that error. Happens on UWP, Android and iOS.

Has anyone else encountered a similar problem?
Thanks

Answers

  • JarvanJarvan Member, Xamarin Team Xamurai

    HttpClient throws a TaskCancelledException for request timeouts and HttpClient does have a Timeout property that you can set. To set the timeout for all requests that use that HttpClient:

    HttpClient client = new HttpClient();
    client.Timeout = TimeSpan.FromSeconds(200); 
    

    Refer to https://stackoverflow.com/questions/53291880/a-task-was-canceled-xamarin-exception

  • AlinMaiorAlinMaior USMember ✭✭

    @yelinzh said:
    HttpClient throws a TaskCancelledException for request timeouts and HttpClient does have a Timeout property that you can set. To set the timeout for all requests that use that HttpClient:

    HttpClient client = new HttpClient();
    client.Timeout = TimeSpan.FromSeconds(200); 
    

    Refer to https://stackoverflow.com/questions/53291880/a-task-was-canceled-xamarin-exception

    I tried that, too.
    I managed to fix that.
    The error lied somewhere else in my code.
    I'm using SignalR and starting multiple connections, the requests started failing after the second SignalR connection. I fixed the code to prevent multiple connections and everything seems to work, now. Thank for the tip, anyway.

Sign In or Register to comment.