Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 573
el_shayan Avatar asked Oct 06 '14 10:10

el_shayan


People also ask

What is the default timeout for HttpWebRequest?

The default value is 100,000 milliseconds (100 seconds).

How do I get HttpWebRequest response?

If you call the GetRequestStream method, you must use the GetResponse method to retrieve the response. If a WebException is thrown, use the Response and Status properties of the exception to determine the response from the server.

What is HttpWebRequest C#?

The HttpWebRequest class provides support for the properties and methods defined in WebRequest and for additional properties and methods that enable the user to interact directly with servers using HTTP.


1 Answers

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.

like image 98
Stephen Cleary Avatar answered Oct 13 '22 16:10

Stephen Cleary