C# – HttpWebRequest times out

chttpwebrequesttimeout

I have read the following 2 articles and have tried implementing the same.

My code is this and the time out occurs here

HttpWebRequest wr = (HttpWebRequest)WebRequest.Create(url);
wr.ContentType = "multipart/form-data; boundary=" + boundary;
wr.Method = "POST";
wr.KeepAlive = false;
wr.CookieContainer = cookieJar;

wr.Proxy = null;
wr.ServicePoint.ConnectionLeaseTimeout = 5000;
Stream rs = wr.GetRequestStream(); // -> Time out error occurs here

Article I read

My code using that as a sample
HttpWebRequest wr = (HttpWebRequest)WebRequest.Create(url);
wr.ContentType = "multipart/form-data; boundary=" + boundary;
wr.Method = "POST";
wr.KeepAlive = false;
wr.CookieContainer = cookieJar;

wr.Timeout = 5000;
wr.Proxy = null;

wr.ServicePoint.ConnectionLeaseTimeout = 5000;
wr.ServicePoint.MaxIdleTime = 5000;

Stream rs = wr.GetRequestStream(); //-->Time out error

Any clues would be helpful. At times I can get 1 request through and all other request fail or everything fails. Am posting to a HTTPS site. No issues when running with Fiddler

UPDATE 1:
I tried following zbugs ideas but that resulted in same issue. the first request goes through the subsequent ones fail. I am closing all response streams as well as calling abort on my request object.

Best Answer

You need to set this.

const int maxIdleTimeout = 5000;
ServicePointManager.MaxServicePointIdleTime = maxIdleTimeout;

If you have more than one client making the request at any given time,

const int maxConnections = 100; //or more/less
ServicePointManager.DefaultConnectionLimit = maxConnections;

http://msdn.microsoft.com/en-us/library/system.net.servicepointmanager.maxservicepointidletime.aspx

Related Topic