iOS Device Crash with System.Net.HttpClient Operation was closed, was canceled, A task was canceled

My app works on the iOS Emulator without problems. But when I started testing on my iOS device, random issues. I believe the problem is HttpClient.PostAsync, since it crashes only when calling the API Service. I get "Operation was closed". The logs in the iOS device wont say much too.

Im using API 2.0 on the backend, and its an azure webapp and making the async call from a PCL.

I followed this thread, and it looked like the problem was resolved but i dont think thats entirely true.

So after reading some, I decided to try with ModernHttpClient and also setting manually the HttpClient.TimeOut with different results:

The operation was canceled -- with ModernHttpClient and manual timeout setting
A task was canceled -- without ModernHttpClient and manual timeout setting

Then, I removed the ModernHttpClient and like magic, just started working. I don't know why, and I didn't make any changes other than adding the component and then removing it, altough its working now, i dont feel very confident as is.

This is the method i was calling when the exceptions started:

    public async Task<UserToken> GetAuthorizationToken()
        HttpClient _client = new HttpClient();
        //_client.Timeout = new TimeSpan(10000);
        _client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

        UserToken token = new UserToken();
            var requestTask = await _client.PostAsync(BaseUrl + "token", Credentials);
            if (requestTask.StatusCode == System.Net.HttpStatusCode.OK)
                await requestTask.Content.ReadAsStringAsync().ContinueWith((readTask) =>
                    token = JsonConvert.DeserializeObject<UserToken>(readTask.Result);
                token.Authenticated = true;
        catch (Exception ex)
        return token;

Any toughts will help.



  • MarekSafarMarekSafar USXamarin Team Xamurai

    Your code looks quite suspicious calling ContinueWith without waiting looks wrong. Why not stick to await and use simple

    token = JsonConvert.DeserializeObject (await requestTask.Content.ReadAsStringAsync())

    If the issue still remains, please fill a bug report with self contained repro.

  • @MarekSafar, It is to my understanding that ContinueWith will continue doing the deserialization asyncroniusly when ReadAsStringAsync finishes. If i'm correct to shouldn't affect at all, BUT next time i ran into trouble, I will definitely try you suggestion.


  • MarekSafarMarekSafar USXamarin Team Xamurai

    @VictorArce.8951 default ContinueWith behaviour is that the continuation task will be queued rather than executed which could lead to issues like yours. There is also TaskContinuationOptions.ExecuteSynchronously to control it but I think await is cleaner in this case

Sign In or Register to comment.