Timeout behaviour in HttpWebRequest.GetResponse()

2019-02-21 11:57发布

问题:

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(); 
});