晚上好!
我正在尝试清理/优化某些代码,最后在Xamarin HTTP请求中找到超时的问题(正如我原来的帖子Async Download and Deserialize中所述)。
发现问题(仅使用Xamarin.Android测试;不了解iOS):
当无法访问主机时(例如,离线本地服务器),GetAsync
在大约 3分钟之后投出System.Net.WebException
消息错误:ConnectFailure(连接超时)。内部异常为System.Net.Sockets.SocketsException
(此处为完整日志:http://pastebin.com/MzHyp2FM)。
代码:
internal static class WebUtilities
{
/// <summary>
/// Downloads the page of the given url
/// </summary>
/// <param name="url">url to download the page from</param>
/// <param name="cancellationToken">token to cancel the download</param>
/// <returns>the page content or null when impossible</returns>
internal static async Task<string> DownloadStringAsync(string url, CancellationToken cancellationToken)
{
try
{
// create Http Client and dispose of it even if exceptions are thrown (same as using finally statement)
using (var client = new HttpClient() { Timeout = TimeSpan.FromSeconds(5) })
{
// should I always do this?
client.CancelPendingRequests();
// Issue here; Timeout of roughly 3 minutes
using (var response = await client.GetAsync(url, cancellationToken).ConfigureAwait(false))
{
// if response was successful (otherwise return null)
if (response.IsSuccessStatusCode)
{
// return its content
return await response.Content.ReadAsStringAsync().ConfigureAwait(false);
}
}
}
}
// TODO: split exceptions?
catch (Exception ex) when (ex is System.Net.Sockets.SocketException ||
ex is InvalidOperationException ||
ex is OperationCanceledException ||
ex is System.Net.Http.HttpRequestException)
{
WriteLine("DownloadStringAsync task has been cancelled.");
WriteLine(ex.Message);
return null;
}
// return null if response was unsuccessful
return null;
}
}
通话方式:
internal static async Task CallAsync(string url)
{
using (var cts = new CancellationTokenSource(TimeSpan.FromSeconds(10)))
{
var token = cts.Token;
token.ThrowIfCancellationRequested();
string result = await WebUtilities.DownloadStringAsync(url, token).ConfigureAwait(false);
}
}
设置client.Timeout
似乎无效。
无论哪种方式,不应该在10秒后自动取消?
此超时问题发生在:
GetAsync
,SendAsync
,
GetResponseAsync
)在以下情况下,代码效果很好:
结论
Xamarin似乎在Http请求中有一些错误(至少有超时?),因为它们没有给出预期的结果。从我读过的内容来看,它可能已经存在了几年(自2012年或2013年)。Xamarin单元测试并没有真正帮助:https://github.com/xamarin/xamarin-android/blob/1b3a76c6874853049e89bbc113b22bc632ed5ca4/src/Mono.Android/Test/Xamarin.Android.Net/HttpClientIntegrationTests.cs
修改
Timeout = TimeSpan.FromMilliseconds(1000)
- 作品Timeout = Timeout = TimeSpan.FromSeconds(1)
- 没有工作(?????)Timeout = TimeSpan.FromMilliseconds(2000)
(及以上) - 没有
工作有什么想法吗?谢谢!
答案 0 :(得分:1)
我发现更改Android的http客户端设置解决了我的问题!我在此处发布了更多详细信息:http://jeremei.com/xamarinvisual-studio-httpclient-request-timeout/