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?
The default value is 100,000 milliseconds (100 seconds).
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With