Timeout exception does not occur on time

796 views Asked by At

I wrote the following code using httpwebrequest(Timeout=2000) and webproxy
The following code always will throw an exception because of wrong url ("ww.google.com")

When I run the program, I get two kinds of exception alternately
1. The remote server returned an error: (404) Not Found (Web Exception)
=> It takes less than 2000ms to catch this exception
=> This exception handling is normal.
.
2. A connection attempt failed because the connected party did not properly respond after a period of time or connected host has failed to respond (Socket Exception)
=> It takes 25 seconds or more to catch this exception
=> I set a request 2000ms timeout but it does not work !!!!

I want to catch exceptions if there is no response within 2 seconds
What should I do?

try 
{ 
       request = (HttpWebRequest)WebRequest.Create("https://ww.google.com"); 
       request.Proxy = proxy; 
       request.Method = "GET"; 
       request.UserAgent = "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.115 Safari/537.36"; 
       request.Timeout = 2000; 
       response = (HttpWebResponse)request.GetResponse(); 
       if ((response.StatusCode == HttpStatusCode.OK || response.StatusCode == HttpStatusCode.Moved || response.StatusCode == HttpStatusCode.Redirect)) 
       { 
              StreamReader sreader = new StreamReader(response.GetResponseStream(), Encoding.Default); 
              gethtml = sreader.ReadToEnd(); 
              sreader.Close(); 
       } 
} 
catch (Exception ex) 
{ 
       throw ex; 
} 
1

There are 1 answers

0
Koby Duck On

Ironically during testing with the invalid url https://ww.google.com you inadvertently tripped a mine. See this post for details. The MSDN documentation referred to in that post is here. Note that WebRequest.Create returns a HttpWebRequest.

Basically, it will take a while because the url isn't mapped to an IP address and thus won't be cached in the chain, requiring a full DNS lookup each time you make a request to it. There's really nothing you can do about this unless you use your own DNS caching layer in the client, but frankly it's more trouble than it's worth.