在C#中出现WinForm原控件Chart卡顿问题
原因:随之加入点的增加数据量也逐步增加
减少reflash()的次数
将原生的Chart控件更换为OxyPlot
using OxyPlot;
using OxyPlot.Axes;
using OxyPlot.Series;
using OxyPlot.WindowsForms;
using System.Threading.Tasks;namespace OxyChart
{public partial class Form1 : Form{public Form1(){InitializeComponent();Load += Form1_Load;}private async void Form1_Load(object? sender, EventArgs e){InitializeOptimizedRealTimeChart();//plotView1.Model =await CreateLineChartAsync();if (plotView1.Model?.Series.Count > 0){// 获取第一个系列(索引为0)var firstSeries = plotView1.Model.Series[0] as LineSeries;if (firstSeries != null){// 添加单个数据点//firstSeries.Points.Add(new DataPoint(1, 10));//firstSeries.Points.Add(new DataPoint(2, 20));//firstSeries.Points.Add(new DataPoint(3, 15));//firstSeries.Points.Add(new DataPoint(4, 25));//firstSeries.Points.Add(new DataPoint(5, 18));for (int i = 0; i < 38400; i++){try{//PTChart.Series[0].Points.AddXY(DateTime.Now, 100);firstSeries.Points.Add(new DataPoint(DateTime.Now.ToOADate(), i));//PTChart.Refresh();plotView1.InvalidatePlot(true);}catch (Exception){}await RelayAsync(1);}// 刷新图表显示}}}private void InitializeOptimizedRealTimeChart(){var model = new PlotModel{Title = "优化版实时数据图表",PlotMargins = new OxyThickness(50, 20, 20, 40)};LineSeries series = new LineSeries{Color = OxyColors.Blue,MarkerFill = OxyColors.Red,LineStyle = LineStyle.Solid,StrokeThickness = 1,MarkerType = MarkerType.Circle,Title = "数据系列" // 添加标题以便识别};// 配置坐标轴//model.Axes.Add(new LinearAxis//{// Position = AxisPosition.Bottom,// Title = "时间",// MajorGridlineStyle = LineStyle.Solid,// MinorGridlineStyle = LineStyle.Dot,// IsPanEnabled = true,// IsZoomEnabled = true//});model.Axes.Add(new DateTimeAxis{Position = AxisPosition.Bottom,Title = "时间",StringFormat = "HH:mm:ss", // 时间格式MajorGridlineStyle = LineStyle.Solid,MinorGridlineStyle = LineStyle.Dot,IsPanEnabled = true,IsZoomEnabled = true});model.Axes.Add(new LinearAxis{Position = AxisPosition.Left,Title = "数值",MajorGridlineStyle = LineStyle.Solid,MinorGridlineStyle = LineStyle.Dot});model.Series.Add(series);plotView1.Model = model;}private async Task<PlotModel> CreateLineChartAsync(){var model = new PlotModel { Title = "折线图示例" };var series1 = new LineSeries{Title = "系列1",MarkerType = MarkerType.Circle};var series2 = new LineSeries{Title = "系列2",MarkerType = MarkerType.Square};// 添加数据点for (int i = 0; i < 100; i++){series1.Points.Add(new DataPoint(i, i));// series2.Points.Add(new DataPoint(i, Math.Cos(i)));await RelayAsync(1);}model.Series.Add(series1);//model.Series.Add(series2);return model;}private async Task RelayAsync(int milliseconds, CancellationToken cancellationToken = default){if (milliseconds < 0){milliseconds = 100;}try{await Task.Delay(milliseconds, cancellationToken);}catch (TaskCanceledException){// 取消操作}}private void button1_Click(object sender, EventArgs e){if (plotView1.Model == null) return;plotView1.Model.DefaultXAxis.Reset();plotView1.Model.DefaultYAxis.Reset();plotView1.InvalidatePlot(true);}}
}
此控件在性能上比原生的Chart控件响应速度快
