2
0

FlowChart.xaml.cs 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. using LiveCharts;
  2. using LiveCharts.Wpf;
  3. using System;
  4. using System.Collections.Generic;
  5. using System.Net.Http;
  6. using System.Threading.Tasks;
  7. using System.Windows.Controls;
  8. namespace FastGithub.UI
  9. {
  10. /// <summary>
  11. /// FlowChart.xaml 的交互逻辑
  12. /// </summary>
  13. public partial class FlowChart : UserControl
  14. {
  15. private readonly LineSeries readSeries = new LineSeries
  16. {
  17. Title = "上行速率",
  18. PointGeometry = null,
  19. Values = new ChartValues<double>()
  20. };
  21. private readonly LineSeries writeSeries = new LineSeries()
  22. {
  23. Title = "下行速率",
  24. PointGeometry = null,
  25. Values = new ChartValues<double>()
  26. };
  27. public SeriesCollection Series { get; } = new SeriesCollection();
  28. public List<string> Labels { get; } = new List<string>();
  29. public Func<double, string> YFormatter { get; } = value => $"{value:0.00}KB/s";
  30. public FlowChart()
  31. {
  32. InitializeComponent();
  33. this.Series.Add(this.readSeries);
  34. this.Series.Add(this.writeSeries);
  35. DataContext = this;
  36. this.InitFlowChart();
  37. }
  38. private async void InitFlowChart()
  39. {
  40. var httpClient = new HttpClient();
  41. while (true)
  42. {
  43. try
  44. {
  45. await this.GetFlowRateAsync(httpClient);
  46. }
  47. catch (Exception)
  48. {
  49. }
  50. finally
  51. {
  52. await Task.Delay(TimeSpan.FromSeconds(1d));
  53. }
  54. }
  55. }
  56. private async Task GetFlowRateAsync(HttpClient httpClient)
  57. {
  58. var response = await httpClient.GetAsync("http://127.0.0.1/flowRates");
  59. var json = await response.EnsureSuccessStatusCode().Content.ReadAsStringAsync();
  60. var flowRate = Newtonsoft.Json.JsonConvert.DeserializeObject<FlowRate>(json);
  61. this.textBlockRead.Text = flowRate.ToTotalReadString();
  62. this.textBlockWrite.Text = flowRate.ToTotalWriteString();
  63. this.readSeries.Values.Add(flowRate.ReadRate / 1024);
  64. this.writeSeries.Values.Add(flowRate.WriteRate / 1024);
  65. this.Labels.Add(DateTime.Now.ToString("HH:mm:ss"));
  66. if (this.Labels.Count > 60)
  67. {
  68. this.readSeries.Values.RemoveAt(0);
  69. this.writeSeries.Values.RemoveAt(0);
  70. this.Labels.RemoveAt(0);
  71. }
  72. }
  73. }
  74. }