Xamarin iOS HttpClient Timeout doesn't work

2019-01-28 08:17发布

问题:

At some point we found all the requests in our app have timeout of 60 seconds on iOS though we set the default value for the HTTP framework we use as 3 minutes. I tried the following piece of code to figure out if it's the library who has an issue:

try
{
    using (var http = new HttpClient())
    {
        http.Timeout = TimeSpan.FromMinutes(1.5);
        await http.GetAsync("https://httpstat.us/200?sleep=70000");
    }
}
catch (Exception ex)
{
}

This code fails with the timeout exception though the timeout is set as 90 sec and the request goes for 70 sec. Turns out it doesn't override the default timeout of 60 sec. The same code works well on the fresh project.

In the project file we have <MtouchHttpClientHandler>NSUrlSessionHandler</MtouchHttpClientHandler>

回答1:

Xamarin's NSUrlSessionHandler uses the default NSUrlSessionConfiguration if you are not creating your own instance of the NSUrlSessionHandler and providing a custom NSUrlSessionConfiguration in its .ctor.

The default NSUrlSessionConfiguration timeouts are set to 60 seconds in iOS.

So in your Xamarin.iOS application project, open the AppDelegate.cs and set the default session timeout parameters within the FinishedLaunching override.

NSUrlSessionConfiguration.DefaultSessionConfiguration.TimeoutIntervalForRequest = 90.0;
NSUrlSessionConfiguration.DefaultSessionConfiguration.TimeoutIntervalForResource = 90.0;

timeoutIntervalForRequest

The timeout interval to use when waiting for additional data.

timeoutIntervalForResource

The maximum amount of time that a resource request should be allowed to take.

re: https://developer.apple.com/documentation/foundation/nsurlsessionconfiguration#//apple_ref/occ/instp/NSURLSessionConfiguration/timeoutIntervalForRequest