Timeout behaviour in HttpWebRequest.GetResponse() vs GetResponseAsync()

僤鯓⒐⒋嵵緔 提交于 2019-12-19 16:10:15

问题


When I try the following code:

var request = (HttpWebRequest)HttpWebRequest.Create(url);
request.Timeout = 3; // a small value

var response = request.GetResponse();
Console.WriteLine(response.ContentLength);

for a URL that I know it is going to take more than 3 millisecond to load (I put a Thread.Sleep(110000) in Application_BeginRequest) it works fine and throws a WebException as expected.

Problem is when I switch to async method:

var response = request.GetResponseAsync().Result;

or

var response = await request.GetResponseAsync();

This async version completely ignores any Timeout value, including ReadWriteTimeout and ServicePoint.MaxIdleTime

I couldn't find anything about Timeout in MSDN's GetResponseAsync() now I'm wondering if it is a bug in GetResponseAsync() or something is wrong in the way I use async here?


回答1:


Timeout does not apply to asynchronous HttpWebRequest requests. To quote the docs:

The Timeout property has no effect on asynchronous requests

I recommend you use HttpClient instead, which was designed with asynchronous requests in mind.




回答2:


Follow a solution to solve the problem.

await Task.Run(() => { 
  var varHttpResponse = varWebRequest.GetResponse(); 
});


来源:https://stackoverflow.com/questions/26214337/timeout-behaviour-in-httpwebrequest-getresponse-vs-getresponseasync

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!