SmallRefactor: Đưa HttpClient ra ngoài vòng lặp tránh bị gọi quá nhiều lần

This commit is contained in:
Le Chau 2020-06-25 09:33:57 +07:00
parent a61195ca03
commit 853c49969d

View File

@ -14,6 +14,7 @@ namespace AIParkingApplication
public partial class Statistic : UserControl public partial class Statistic : UserControl
{ {
private const string AIPARKING_CLIENT_HTTP_API_REQUEST = "http://{0}:{1}{2}"; private const string AIPARKING_CLIENT_HTTP_API_REQUEST = "http://{0}:{1}{2}";
private readonly HttpClient client = new HttpClient { BaseAddress = new Uri("http://192.168.1.123:80/"), Timeout = TimeSpan.FromMilliseconds(5000) };
Label lblLoaiXe; Label lblLoaiXe;
Label lblXeMay; Label lblXeMay;
@ -43,28 +44,26 @@ namespace AIParkingApplication
{ {
try try
{ {
using (var client = new HttpClient { BaseAddress = new Uri("http://192.168.1.123:80/"), Timeout = TimeSpan.FromMilliseconds(5000) }) HttpResponseMessage response = await client.GetAsync("/api/statistics");
response.EnsureSuccessStatusCode();
var vehicle = await response.Content.ReadAsAsync<Vehicle>();
lblSoLuongXeMay?.Invoke(new Action(() =>
{ {
HttpResponseMessage response = await client.GetAsync("/api/statistics"); lblSoLuongXeMay.Text = vehicle.NumberOfMoto.ToString();
response.EnsureSuccessStatusCode(); }));
var vehicle = await response.Content.ReadAsAsync<Vehicle>(); lblSoLuongOto?.Invoke(new Action(() =>
lblSoLuongXeMay?.Invoke(new Action(() => {
{ lblSoLuongOto.Text = vehicle.NumberOfCar.ToString();
lblSoLuongXeMay.Text = vehicle.NumberOfMoto.ToString(); }));
})); lblVehicleTotalIn?.Invoke(new Action(() =>
lblSoLuongOto?.Invoke(new Action(() => {
{ lblVehicleTotalIn.Text = vehicle.TotalIn;
lblSoLuongOto.Text = vehicle.NumberOfCar.ToString(); }));
})); lblVehicleTotalOut?.Invoke(new Action(() =>
lblVehicleTotalIn?.Invoke(new Action(() => {
{ lblVehicleTotalOut.Text = vehicle.TotelOut;
lblVehicleTotalIn.Text = vehicle.TotalIn; }));
}));
lblVehicleTotalOut?.Invoke(new Action(() =>
{
lblVehicleTotalOut.Text = vehicle.TotelOut;
}));
}
} }
catch (Exception ex) catch (Exception ex)
{ {
@ -102,7 +101,7 @@ namespace AIParkingApplication
[JsonProperty("moto")] [JsonProperty("moto")]
public int NumberOfMoto { get; set; } public int NumberOfMoto { get; set; }
[JsonProperty("total_in")] [JsonProperty("total_in")]
public string TotalIn { get; set; } public string TotalIn { get; set; }