user131008
user131008

Reputation: 77

WebRequest.Timeout not working as expected

var strURL = "http://999.999.999.999"; // invalid IP-address
System.Net.WebResponse objResponse = default(System.Net.WebResponse);
System.Net.WebRequest objRequest = default(System.Net.WebRequest);

objRequest = System.Net.HttpWebRequest.Create(strURL);
objRequest.Timeout = 100;
objResponse = objRequest.GetResponse();

System.IO.StreamReader sr = new System.IO.StreamReader(objResponse.GetResponseStream());
result = sr.ReadToEnd();

The timeout I see through firebug is 3000 miliseconds... It shouldn't be that way!

Upvotes: 1

Views: 7909

Answers (3)

Jeff Codes
Jeff Codes

Reputation: 77

The timeout property is to be set to milliseconds. By setting to "100" your timeout is set to 0.1 seconds (100 milliseconds). Try setting to something more reasonable such as 30 seconds (30,000 milliseconds) or just don't explicitly set and leave as the default 100,000 ms.

From MSDN

Upvotes: 0

laifukang
laifukang

Reputation: 311

Your issue lies in the pre-request resolution of the invalid IP address. All normal requests timeout normally. As per MSDN:

A Domain Name System (DNS) query may take up to 15 seconds to return or time out. If your request contains a host name that requires resolution and you set Timeout to a value less than 15 seconds, it may take 15 seconds or more before a WebException is thrown to indicate a timeout on your request.

True, '999.999.999.999' does not require a DNS lookup, but the Request object must be getting confused and taking a while to resolve it. If the IP is changed to a valid URL:

var strURL = "http://www.myjunkinvalidurl.com"; 

or a valid, functioning IP:

var strURL = "http://134.170.188.221"; // microsoft.com

or a valid, non-functioning IP:

var strURL = "http://123.123.123.123"; 

all come back within about 115ms (with a 100ms timeout), so there must be an issue with WebRequest's invalid IP address resolution, which comes back in about 2300ms for me. Keep the IP valid and you should be fine.

Upvotes: 3

Manikandan Sigamani
Manikandan Sigamani

Reputation: 1984

According to http://msdn.microsoft.com/en-us/library/system.net.httpwebrequest.timeout.aspx The number of milliseconds to wait before the request times out. The default value is 100,000 milliseconds (100 seconds).

Upvotes: -2

Related Questions