我有以下代码:
public static string createRequest(string url, int timeout = 1)
{
Task<string> responseString;
using (var client = new System.Net.Http.HttpClient())
{
responseString = client.GetStringAsync(url);
responseString.Wait(new TimeSpan(0, 0, timeout));
}
}如果我第一次在调试器中运行这段代码,超时只会在很长一段时间(1-2分钟)之后发生。第二次,它跑得更快,在3-4秒后结束.
如果在这次调用之后在某些代码上设置一个断点,它有时运行得更快,但主要是需要很长时间。
为什么即使有定义的超时,代码也要花这么长的时间呢?
事实上,responseString.Status是TaskStatus.Canceled,这正是我所期望的(没有绑定到这个IP的设备)。
这个代码有什么问题?谢谢您:)
发布于 2015-12-15 14:55:35
不应设置Task<string>对象的超时。你必须设置HttpClient.Timeout。此外,请考虑使用异步/等待方法:
public static async Task<string> createRequest(string url, int timeout = 1)
{
using(var client = new HttpClient())
{
client.Timeout = TimeSpan.FromSeconds(timeout);
string response = await client.GetStringAsync(url);
// Handle response here
return handledResponse; // You can return a raw string
}
}发布于 2015-12-16 07:58:33
也许不是最美丽的版本,但完全符合我的预期:
public string AsyncRequest(string url, int timeout)
{
string retval = null;
using (var client = new System.Net.Http.HttpClient())
{
client.Timeout = TimeSpan.FromSeconds(timeout);
try
{
retval = client.GetStringAsync(url).Result;
return retval;
}
catch
{
AllnetALL3073RemoteSwitch_found = false;
return null;
}
}
}https://stackoverflow.com/questions/34292089
复制相似问题