Your PC can't even




C# - Variable Timeout Web Client

This article shows how to extend WebClient in order to have it to accept a paramter which changes the timeout (in minutes).

How is this useful?

  • I’ve had to interface with APIs that have an extended wait time when calling the endpoint. Generally these are batch processes responsible for syncing data in various systems and require we wait for a response as opposed to being fire-and-forget (async). In these instances, I've needed to have a webclient capable of waiting longer than the default timeout(about 100 seconds).

Implementing the class

		

public class VariableTimeout : System.Net.WebClient
{
    private  int _minutes;
    private  int _millis {get{return _minutes * 60000;}}
    public VariableTimeout(int minutes){
        this._minutes = minutes;
    }
    protected override System.Net.WebRequest GetWebRequest(Uri address){
        System.Net.WebRequest w = base.GetWebRequest(address);
        w.Timeout = this._millis;
        return w;
        return request;
    }
}

Usage...
Calling an API endpoint.

using (var Client = new VariableTimeout(5))
{
    string SiteBase = "https://somewebapi.domain.net";
    string content = "application/x-www-form-urlencoded";
    Client.Headers.Add("Content-Type", content);
    //Use our cookie to verify authentication
    string resp2 = Encoding.UTF8.GetString(Client.DownloadData(string.Format("{0}/SomePath/SomeEndpoint", SiteBase)));
}