I have an ASP.NET web forms app running on IIS 8. The app uses HttpClient to retrieve data from a server. And that is all. HttpClient is not used thereafter.
Do I need to dispose of the HttpClient at this point?
I am really confused, because people on the internet are saying that you shouldn't, as this allows the HttpClient instance to be reused. But in my case, reused by what? By another request to my app? But surely the HttpClient instantiated in one request cannot be reused by another request.
Here is the code:
public class PendingOrderDataAccessLayer {
static HttpClient client = new HttpClient();
readonly string GetPendingOrdersUrl = "noneOfYourBusiness.com";
public PendingOrderDataAccessLayer() {
// We have to do this, otherwise we get an TLS exception.
System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
}
public List<PendingOrder> GetPendingOrders() {
try {
string json = GetJson();
var pendinOrders = new List<PendingOrder>();
dynamic dynJson = JsonConvert.DeserializeObject(json);
foreach (var pendingOrder in dynJson) {
foreach (var product in pendingOrder["product_list"]) {
pendinOrders.Add(new PendingOrder() {
CustomerName = pendingOrder["customer_name"] == " " ? "Anonymous IVR Customer" : pendingOrder["customer_name"],
CustomerNo = pendingOrder["customer_no"],
IPAddress = pendingOrder["ipaddress"],
OrderNo = pendingOrder["order_no"],
SKU = product["sku"],
PendMinutes = product["pend_time"],
ProductName = product["product_title"],
Qty = product["qty"],
DateTime = DateTime.ParseExact($"{pendingOrder["date"]} {pendingOrder["time"]}", "dd/MM/yyyy hh:mmtt", null)
});
}
}
return pendinOrders;
}
catch (Exception e) {
ExHandler.Get().HandleException($"Problem occurred while getting JSON list of pending orders. The URL is {GetPendingOrdersUrl}", e);
throw;
}
}
string GetJson() {
return client.GetStringAsync(GetPendingOrdersUrl).Result;
}
}
Should I not dispose of the HttpClient when the GetPendingOrders method is done? It will not be used thereafter.