Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to limit the time DownloadString(url) allowed by 500 milliseconds?

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.

like image 351
Thanh Nguyen Avatar asked Oct 14 '12 02:10

Thanh Nguyen


2 Answers

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);
like image 169
bytebuster Avatar answered Oct 30 '22 01:10

bytebuster


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.

like image 29
Stephen Hewlett Avatar answered Oct 30 '22 01:10

Stephen Hewlett