After making a lot of network requests in a short space of time, we keep getting "A task was canceled" error from our responses, once we start getting these errors any requests made after the errors stop return the same errors too until we restart the app. We use an AuthenticatedHttpClientHandler
to handle auth tokens in our requests:
public class AuthenticatedHttpClientHandler : HttpClientHandler
{
private readonly IReauthService _reauthService;
public AuthenticatedHttpClientHandler(IReauthService reauthService)
{
_reauthService = reauthService;
}
protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
Debug.WriteLine("Url: " + request.RequestUri);
var auth = request.Headers.Authorization;
if (auth != null)
{
string token = await _reauthService.GetToken();
request.Headers.Authorization = new AuthenticationHeaderValue(auth.Scheme, token);
}
try
{
//Error occurs on this line
HttpResponseMessage resp = await base.SendAsync(request, cancellationToken).ConfigureAwait(false);
return resp;
}
catch (Exception e)
{
//this.GetLogger().LogToDebugConsole("FAILED: " + request.Method + " " + request.RequestUri);
//this.GetLogger().LogToDebugConsole("Reason: " + e.Message);
//this.GetLogger().LogToDebugConsole("Stacktrace: " + e.StackTrace);
Crashes.TrackError(e);
throw new RequestFailedException(e);
}
}
}
We use this like so:
container.RegisterSingleton(() =>
{
var handler = container.Resolve<AuthenticatedHttpClientHandler>();
HttpClient client = new HttpClient(handler)
{
BaseAddress = new Uri(UrlConfig.MobileApiBaseUrl + UrlConfig.Version),
Timeout = TimeSpan.FromSeconds(30)
};
var service = RestService.For<IMobileApiClient>(client);
return service;
});
The 30s timeout is not the issue as all our requests are under 2s and we can reproduce the errors consistently.
A single HttpClient
instance is used for every call. We also use MvvmCross and the issue appears to only be on iOS. We have tried changing the HttpClientImplementation in our project settings, as well using a new instance of HttpClient
in every call but neither have worked.
Full Stacktrace:
==========A task was canceled.==========
========== at System.Net.Http.MonoWebRequestHandler.SendAsync (System.Net.Http.HttpRequestMessage request, System.Threading.CancellationToken cancellationToken) [0x004ac] in /Library/Frameworks/Xamarin.iOS.framework/Versions/Current/src/Xamarin.iOS/mcs/class/System.Net.Http/MonoWebRequestHandler.cs:507
at CustomerApp.Core.Networking.LoggingAuthenticatedHttpClientHandler.SendAsync (System.Net.Http.HttpRequestMessage request, System.Threading.CancellationToken cancellationToken) [0x0059f] in /Users/user/VSProjects/CustomerApp/CustomerApp.Core/Networking/AuthenticatedHttpClientHandler.cs:38 ==========
Build settings: