0

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.

David Rogers
  • 2,601
  • 4
  • 39
  • 84
JRG
  • 210
  • 1
  • 10
  • HttpClient is thread-safe. Also, why isn’t your code using `async`? – Dai Mar 21 '19 at 23:45
  • The method GetPendingOrders is not async because were it to be, then ObjectDataSource binding would not work. https://learn.microsoft.com/en-us/dotnet/api/system.web.ui.webcontrols.objectdatasource?view=netframework-4.7.2 EDIT: it might be possible actually (https://devblogs.microsoft.com/aspnet/cool-asp-net-web-forms-features-in-2015-async-model-binding/) i will have a look. – JRG Mar 21 '19 at 23:47
  • Ah, you’re using WebForms. You have my sympathy. – Dai Mar 21 '19 at 23:48
  • You should use HttpWebRequest then instead of HttpClient, IMO. – Dai Mar 21 '19 at 23:48
  • Ok, I will look into HttpWebRequest. Thanks – JRG Mar 22 '19 at 00:01
  • @Dai Actually, I just learned that static variables are shared by all requests in an app domain. That means that every request that comes to my app will use the same HttpClient instance. This is OK i think. So no need to dispose it. – JRG Mar 22 '19 at 00:55
  • Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/190468/discussion-between-jrg-and-dai). – JRG Mar 22 '19 at 00:58
  • Use Flurl. Then you won't have to worry about this. It will handle it for you, and has a cleaner API. Of course if you're going to use asynchronous code, then you need to go async all the way up and down the call stack. Don't access .Result. Await the async calls instead. – mason Mar 22 '19 at 04:24

0 Answers0