C#:用下载一个超时网址 [英] C#: Downloading a URL with timeout

查看:224
本文介绍了C#:用下载一个超时网址的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

什么是做它在.NET的最佳方式?
我总是忘了什么,我需要的Dispose()(或使用带有包装)。

What's the best way to do it in .NET? I always forget what I need to Dispose() (or wrap with using).

编辑:使用时间长了以后的WebRequest ,我发现了定制 Web客户端。好多了。

after a long time using WebRequest, I found out about customizing WebClient. Much better.

推荐答案

继托马斯·莱维斯克的评论<一个href=\"http://stackoverflow.com/questions/1469805/c-canonical-http-post-$c$c/1474861#1474861\">here,还有一个更简单,更通用的解决方案。

Following Thomas Levesque's comment here, there's a simpler and more generic solution.

我们创建超时支持 Web客户端子类,我们得到了所有的WebClient 的善良。

We create a WebClient subclass with timeout support, and we get all of WebClient's goodness.

public class WebClientWithTimeout : WebClient
{
  private readonly int timeoutMilliseconds;
  public WebClientWithTimeout(int timeoutMilliseconds)
  {
    this.timeoutMilliseconds = timeoutMilliseconds;
  }

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

使用范例:

public string GetRequest(Uri uri, int timeoutMilliseconds)
{
  using (var client = new WebClientWithTimeout(timeoutMilliseconds))
  {
    return client.DownloadString();
  }
}

这篇关于C#:用下载一个超时网址的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆