Real Time
Razor
@page "/General/RealTime"
@using LiveChartsCore.SkiaSharpView.Blazor
@using LiveChartsCore;
@using LiveChartsCore.Defaults;
@using LiveChartsCore.SkiaSharpView;
@using LiveChartsCore.SkiaSharpView.Painting;
@using SkiaSharp;
@using System.Collections.ObjectModel
<CartesianChart
@ref="_chart"
Series="@series"
XAxes="@xAxes"
SyncContext="_sync">
</CartesianChart>
@code {
private CartesianChart _chart;
private ObservableCollection<DateTimePoint> _values = new ObservableCollection<DateTimePoint>();
private object _sync = new object();
private bool _isReading = true;
private double[] _separators = new double[0];
private ISeries[] series;
private Axis[] xAxes;
protected override void OnInitialized()
{
series = new ISeries[]
{
new LineSeries<DateTimePoint>
{
Values = _values,
Fill = null,
GeometryFill = null,
GeometryStroke = null
}
};
var xAxis = new Axis
{
Labeler = value => Formatter(new DateTime((long)value)),
AnimationsSpeed = TimeSpan.FromMilliseconds(0),
SeparatorsPaint = new SolidColorPaint(SKColors.Gray),
CustomSeparators = _separators
};
xAxes = new Axis[] { xAxis };
_ = ReadData(xAxis);
}
private async Task ReadData(Axis xAxis)
{
var random = new Random();
while (_isReading)
{
await Task.Delay(100);
lock (_sync)
{
_values.Add(new DateTimePoint(DateTime.Now, random.Next(0, 10)));
if (_values.Count > 250) _values.RemoveAt(0);
_separators = GetSeparators();
xAxis.CustomSeparators = _separators;
}
}
}
private static double[] GetSeparators()
{
var now = DateTime.Now;
return new double[]
{
now.AddSeconds(-25).Ticks,
now.AddSeconds(-20).Ticks,
now.AddSeconds(-15).Ticks,
now.AddSeconds(-10).Ticks,
now.AddSeconds(-5).Ticks,
now.Ticks
};
}
private static string Formatter(DateTime date)
{
var secsAgo = (DateTime.Now - date).TotalSeconds;
return secsAgo < 1 ? "now" : $"{secsAgo:N0}s ago";
}
}
Articles you might also find useful: