17

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?

el_shayan
  • 2,735
  • 4
  • 28
  • 42
  • see answer in http://stackoverflow.com/questions/4238345/asynchronously-wait-for-taskt-to-complete-with-timeout – artm Oct 06 '14 at 10:31
  • Does it mean they intentionally ignore Timeout in all async APIs? I find that hard to believe. For example in this specific case this leaves the API user with no way to set different timeout values for different stages like ReadWriteTimeout/ContinueTimeout – el_shayan Oct 06 '14 at 10:37

2 Answers2

24

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.

Stephen Cleary
  • 437,863
  • 77
  • 675
  • 810
  • 4
    "The Timeout property has no effect on asynchronous requests **made with the BeginGetResponse or BeginGetRequestStream method.**": docs are not about GetResponseAsync, but answer is right anyway, because GetResponseAsync uses BeginGetResponse inside. – VorobeY1326 Nov 28 '14 at 12:52
0

Follow a solution to solve the problem.

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