2

Now I am using HttpWebRequest.BeginGetResponse method for http call, I want to migrate the code to async-await model. So, though of using WebClient.DownloadStringTaskAsync method, but not sure how to set timeout?

Rook
  • 5,734
  • 3
  • 34
  • 43
Raghu
  • 111
  • 2
  • 7
  • 1
    Possible duplicate of [Asynchronously wait for Task to complete with timeout](https://stackoverflow.com/questions/4238345/asynchronously-wait-for-taskt-to-complete-with-timeout) – Rook Sep 22 '18 at 16:51

1 Answers1

4

The default timeout for WebClient is 100 seconds (i believe)

  • If you like you can CancelAsync() with your own timeout, add pepper and salt to taste.

  • You use HttpWebRequest rather than WebClient (it uses the HttpWebRequest internally). Using the HttpWebRequest will allow you to set the timeout implicitly.

  • You could make a derived class which sets the timeout for the WebRequest as seen from this answer

Set timeout for webClient.DownloadFile()

public class WebDownload : WebClient
{
    /// <summary>
    /// Time in milliseconds
    /// </summary>
    public int Timeout { get; set; }

    public WebDownload() : this(60000) { }

    public WebDownload(int timeout)
    {
        this.Timeout = timeout;
    }

    protected override WebRequest GetWebRequest(Uri address)
    {
        var request = base.GetWebRequest(address);
        if (request != null)
        {
            request.Timeout = this.Timeout;
        }
        return request;
    }
}
TheGeneral
  • 79,002
  • 9
  • 103
  • 141