在短时间内发出大量网络请求后,我们的响应中不断收到“任务已取消”错误,一旦我们开始收到这些错误,在错误停止后发出的任何请求也会返回相同的错误,直到我们重新启动应用程序。我们使用 anAuthenticatedHttpClientHandler
来处理请求中的身份验证令牌:
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);
}
}
}
我们像这样使用它:
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;
});
30 秒超时不是问题,因为我们所有的请求都在 2 秒以下,我们可以一致地重现错误。
HttpClient
每次调用都使用一个实例。我们也使用 MvvmCross,而且这个问题似乎只出现在 iOS 上。我们尝试在项目设置中更改 HttpClientImplementation,并HttpClient
在每次调用中使用新实例,但均未奏效。
完整的堆栈跟踪:
==========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 ==========
构建设置: