我正在开发一个遗留的Windows窗体应用程序,我对http客户端进行了一些更改,我希望将其作为一个单例,以便在整个应用程序中重用。这似乎造成了僵局。
我将粘贴我认为涉及的所有代码:
这是UI被冻结的调用代码,它从不解冻。
private async void lbGroup_SelectedIndexChanged_1(object sender, EventArgs e) { int groupId = this.lbGroup.SelectedIndex + 1; await LoadStores(groupId); //The code below freezes the application this.lbStore.DataSource = _stores; this.txtSearch.Enabled = true; this.lbStore.Enabled = true; }
这是使用httpClient的LoadStores方法:
private async Task LoadStores(int group) { try { HttpResponseMessage res = await _httpClient.GetAsync("api/GetStoresByGroup/" + group.ToString()); res.EnsureSuccessStatusCode(); if (res.IsSuccessStatusCode) { var serializedStores = await res.Content.ReadAsStringAsync(); _stores = JsonConvert.DeserializeObject<IEnumerable<Store>>(serializedStores).Select(s => s.StoreName).ToList(); res.Content.Dispose(); } } catch (Exception ex) { ErrorLogger.LogError("Installation", $"Error getting stores list: {ex.Message}"); } }
这是Http Singleton类:
public static class HttpClientSingleton { private static readonly HttpClient _instance; static HttpClientSingleton() { _instance = new HttpClient(); _instance.BaseAddress = new Uri("https://www.i-city.co.za/"); _instance.DefaultRequestHeaders.Accept.Clear(); _instance.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json")); } public static HttpClient Instance { get { return _instance; } } }
这是初始化HttpClient的表单构造函数:
public partial class frmInstallationHelper : Form { private static string _configDir; private static string _localConfigDir; private static int _storeID; private static Activation _activation; private static HttpClient _httpClient = HttpClientSingleton.Instance; private static IEnumerable<string> _stores; private static IEnumerable<string> _franchisees; private int _smsCounter;
如果我将http请求包装在LoadStores方法内部的using语句中,那么应用程序运行良好,但我不想丢弃http客户端,因为这会破坏将其作为单例的目的。