我是否必须完全配置HTTP客户端?

时间:2019-03-21 23:38:37

标签: c# httpclient dispose

我有一个在IIS 8上运行的ASP.NET Web窗体应用程序。该应用程序使用HttpClient从服务器检索数据。仅此而已。此后不使用HttpClient。

此时我是否需要丢弃HttpClient?

我真的很困惑,因为互联网上的人们都说你不应该这样做,因为这样可以重用HttpClient实例。但是就我而言,被什么重用了?通过对我的应用程序的另一个请求?但是可以肯定的是,在一个请求中实例化的HttpClient不能被另一个请求重用。

代码如下:

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;
        }
    }

完成GetPendingOrders方法后,是否应该不处理HttpClient?此后将不再使用。

0 个答案:

没有答案