Tuesday, September 6, 2011

[Solution] WebClient or WebRequest freezes or times out after second request

One of the most common reasons is that WebClient or WebRequest has reached the maximum number of connections that .NET Framework can make to a HTTP server (by default it is 2 connections). In other words, if program submit multiple requests to the same address, then only two first requests are actually sent, and the rest are queued up.


Solution 1: Increase limit globally


public partial class MainForm : Form
{
    public MainForm()
    {
        InitializeComponent();
    }

    private void MainForm_Load(object sender, EventArgs e)
    {
        ServicePointManager.DefaultConnectionLimit = 100;

    ...


Solution 2: Icrease limit per server


protected override WebRequest GetWebRequest(Uri address)
{
    WebRequest webRequest = base.GetWebRequest(address);

    HttpWebRequest httpWebRequest = webRequest as HttpWebRequest;

    if (httpWebRequest != null)
    {
        httpWebRequest.ServicePoint.ConnectionLimit = 100;
    }

    ...

No comments:

Post a Comment