Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
376 views
in Technique[技术] by (71.8m points)

c# - 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...