有时我们发现我们的应用程序中的所有请求在 iOS 上都有 60 秒的超时时间,尽管我们将使用的 HTTP 框架的默认值设置为 3 分钟.我尝试了以下代码来确定是否是图书馆有问题:
试试{使用 (var http = new HttpClient()){http.Timeout = TimeSpan.FromMinutes(1.5);等待 http.GetAsync("httpstat.us/200?sleep=70000");}}捕获(异常前){}尽管超时设置为 90 秒且请求持续 70 秒,但此代码因超时异常而失败.事实证明它不会覆盖 60 秒的默认超时.相同的代码在新项目上运行良好.
在项目文件中我们有 NSUrlSessionHandler
解决方案Xamarin 的 NSUrlSessionHandler 使用 default NSUrlSessionConfiguration自己的 NSUrlSessionHandler 实例并在其 .ctor 中提供自定义 NSUrlSessionConfiguration.
iOS 中默认的 NSUrlSessionConfiguration 超时设置为 60 秒.
因此,在您的 Xamarin.iOS 应用程序项目中,打开 AppDelegate.cs 并在 FinishedLaunching 覆盖中设置默认会话超时参数.
NSUrlSessionConfiguration.DefaultSessionConfiguration.TimeoutIntervalForRequest = 90.0;NSUrlSessionConfiguration.DefaultSessionConfiguration.TimeoutIntervalForResource = 90.0;timeoutIntervalForRequest
等待额外数据时使用的超时间隔.timeoutIntervalForResource
应允许资源请求占用的最长时间.re: developer.apple/documentation/foundation/nsurlsessionconfiguration#//apple_ref/occ/instp/NSURLSessionConfiguration/timeoutIntervalForRequest
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("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>
解决方案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: developer.apple/documentation/foundation/nsurlsessionconfiguration#//apple_ref/occ/instp/NSURLSessionConfiguration/timeoutIntervalForRequest
更多推荐
Xamarin iOS HttpClient 超时不起作用
发布评论