Showing posts with label Timeout. Show all posts
Showing posts with label Timeout. Show all posts

Friday, May 4, 2012

Configuring WebClient Timeout and ConnectionLimit

Simplicity is nice, but not when it comes at the expense off accomplishing your goal.

Recently I have been using System.Net.WebClient to access some REST APIs. It is great how simple the WebClient class is to use, but unfortunately it does not natively support configuring it's timeout or connection limit. In fact, before I knew that the default connection limit was preventing me from making more than two concurrent requests at a time, it was actually causing me some serious issues while doing performance testing.

Good news, both of these issues are very easy to fix by simply extending the WebClient class.

Sample Class

public class ConfigurableWebClient : WebClient
{
    public int? Timeout { get; set; }
    public int? ConnectionLimit { get; set; }
        
    protected override WebRequest GetWebRequest(Uri address)
    {
        var baseRequest = base.GetWebRequest(address);
        var webRequest = baseRequest as HttpWebRequest;
        if (webRequest == null)
            return baseRequest;
 
        if (Timeout.HasValue)
            webRequest.Timeout = Timeout.Value;
 
        if (ConnectionLimit.HasValue)
            webRequest.ServicePoint.ConnectionLimit = ConnectionLimit.Value;
 
        return webRequest;
    }
}
kick it on DotNetKicks.com

Enjoy,
Tom

Real Time Web Analytics