18

I'm writing a program that when textBox1 change:

URL = "http://example.com/something/";
URL += System.Web.HttpUtility.UrlEncode(textBox1.Text);
s = new System.Net.WebClient().DownloadString(URL);

I want limit the time DownloadString(URL) allowed by 500 milliseconds. If more than, cancel it.

Cœur
  • 37,241
  • 25
  • 195
  • 267
NoName
  • 7,940
  • 13
  • 56
  • 108

2 Answers2

38

There is no such property, but you can easily extend the WebClient:

public class TimedWebClient: WebClient
{
    // Timeout in milliseconds, default = 600,000 msec
    public int Timeout { get; set; }

    public TimedWebClient()
    {
        this.Timeout = 600000; 
    }

    protected override WebRequest GetWebRequest(Uri address)
    {
        var objWebRequest= base.GetWebRequest(address);
        objWebRequest.Timeout = this.Timeout;
        return objWebRequest;
    }
}

// use
string s = new TimedWebClient {Timeout = 500}.DownloadString(URL);
Be Brave Be Like Ukraine
  • 7,596
  • 3
  • 42
  • 66
  • Had a problem with a popular currency rates site, site allowed conneciton but their API did not send a response - this little nugget is the ideal patch, much obliged. – Steve Hibbert Dec 03 '14 at 10:30
  • 1
    Now I look again and learned enough to know your answer diriectly answer my question. Change accecpted to your answer. – NoName Feb 29 '16 at 01:06
7

One way to do this would be to use the DownloadStringAsync method on the WebClient class, and then asynchronously call the CancelAsync method after 500 milliseconds. See the remarks section here for some pointers on how to do that.

Alternatively, you could use the WebRequest class instead, which has a Timeout property. See the code example here.

Stephen Hewlett
  • 2,415
  • 1
  • 18
  • 31