Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In C# how to set timeout while using WebClient.DownloadStringTaskAsync method?

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?

like image 597
Raghu Avatar asked Aug 15 '26 09:08

Raghu


1 Answers

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;
    }
}
like image 77
TheGeneral Avatar answered Aug 16 '26 22:08

TheGeneral



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!