Zayko in the Net

Personal blog of Vitaly Zayko

NAVIGATION - SEARCH

Setting Request timeout interval in WebClient (C#)

Most programmers who work with remote HTTP services prefer to use WebClient over WebRequest/WebResponse because of its simplicity. The only WebClient's feature I missed is ability to customize request timeout interval but fortunatelly it is very easy to fix by creating own class derived from WebClient. Here is how....

 public  class  WebClientEx  : WebClient
  {
     // Timeout in milliseconds
      public  int  Timeout { get ; set ; }
 
     /// <summary>
      /// Sets default timeout
      /// </summary>
      public  WebClientEx()
         : base ()
     {
         this .Timeout = 10000;
     }
 
     /// <summary>
      /// Sets custom timeout
      /// </summary>
      /// <param name="timeout">Timeout in milliseconds</param>
      public  WebClientEx(int  timeout)
         : base ()
     {
         this .Timeout = timeout;
     }
 
     /// <summary>
      /// Overriding base method to set timeout
      /// </summary>
      /// <param name="address">Server Url</param>
      /// <returns>A WebRequest with a timeout assigned</returns>
      protected  override  WebRequest  GetWebRequest(Uri  address)
     {
         WebRequest  wr = base .GetWebRequest(address);
         wr.Timeout = this .Timeout;
         return  wr;
     }
 }
 

Add comment