Search code examples
c#httpwebrequesttimeoutwebrequest.net-3.0

C#: Downloading a URL with timeout


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

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


Solution

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

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

    Sample usage:

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