Sachin Singh

Sachin Singh

  • 10
  • 55.8k
  • 75.2k

Best way to instantiate a HttpClient in winform and webforms.

Sep 13 2020 9:41 AM
As per MSDN
 
HttpClient is intended to be instantiated once and re-used throughout the life of an application. Instantiating an HttpClient class for every request will exhaust the number of sockets available under heavy loads. This will result in SocketException errors. Below is an example using HttpClient correctly.
  1. public class GoodController : ApiController    
  2. {    
  3.     private static readonly HttpClient HttpClient;    
  4.     
  5.     static GoodController()    
  6.     {    
  7.         HttpClient = new HttpClient();    
  8.     }    
  9. }       
But in windows form (obviously controller doen't make sense here) or Webform we do not have controller , however in webform we can store instance of HttpClient in the Application property to use a single instance in all requests.
  1. Application.Add("_Client"new HttpClient()); 
 The other approach can be creating a singleton class like
  1. public class ClientInstantiator  
  2. {  
  3.     // OK  
  4.     private static readonly HttpClient _Client;  
  5.   
  6.     static ClientInstantiator  ()  
  7.     {  
  8.         _Client = new HttpClient();  
  9.     }  

 But in winform nothing make sense.
Am i over analyzing things?? as msdn also says that almost all useful async methods of HttpClient are thread safe like
  • CancelPendingRequests
  • DeleteAsync
  • GetAsync
  • GetByteArrayAsync
  • GetStreamAsync
  • GetStringAsync
  • PostAsync
  • PutAsync
  • SendAsync