2
0

FlowChart.xaml.cs 2.8 KB

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