如何将DownloadString(url)的允许时间限制在500毫秒内?

18

我正在编写一个程序,当textBox1改变时:

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

我想限制DownloadString(URL)函数的执行时间不超过500毫秒。如果超过了,就取消它。

2个回答

38

没有这样的属性,但是你可以轻松地扩展 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);

遇到了一个流行的货币汇率网站的问题,该网站允许连接但其API没有发送响应 - 这个小技巧是理想的补丁,非常感谢。 - Steve Hibbert
1
现在我再看一遍,已经学到足够的知识来理解你的回答直接回答了我的问题。我将接受你的答案。 - Thanh Nguyen

7

一种方法是使用WebClient类上的DownloadStringAsync方法,然后在500毫秒后异步调用CancelAsync方法。有关如何执行此操作的一些提示,请参见备注部分here

或者,您可以改用具有Timeout属性的WebRequest类。请参见代码示例here


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接