[C#] Blazor练习 实时曲线

2022-12-01 10:15:12 浏览数 (1)

代码语言:javascript复制
@page "/chart/live-chart"
@using Syncfusion.Blazor
@using Syncfusion.Blazor.Charts
@using System.Collections.ObjectModel
@using System.Collections.Specialized
@using System.Timers
@inject NavigationManager NavigationManager
<div class="control-section" align="center">
    <SfChart @ref="liveChart" Title="CPU_Usage" Width="@Width" Theme="@theme">
        <ChartPrimaryXAxis ValueType="Syncfusion.Blazor.Charts.ValueType.DateTime" LabelFormat="mm:ss" Title="Time (s)">
            <ChartAxisMajorGridLines Width="0"></ChartAxisMajorGridLines>
        </ChartPrimaryXAxis>
        <ChartArea>
            <ChartAreaBorder Width="0"></ChartAreaBorder>
        </ChartArea>
        <ChartPrimaryYAxis Title="Usage" Minimum="0" Interval="20" Maximum="100" LabelFormat="{value}%">
            <ChartAxisLineStyle Width="0" Color="transparent"></ChartAxisLineStyle>
        </ChartPrimaryYAxis>
        <ChartSeriesCollection>
            <ChartSeries Type="ChartSeriesType.Line" Width="2" DataSource="@DataPoints"
                         XName="@nameof(ChartDataPoint.Time)" YName="@nameof(ChartDataPoint.CPU_Usage)">
                <ChartSeriesAnimation Enable="false"></ChartSeriesAnimation>
            </ChartSeries>
        </ChartSeriesCollection>
    </SfChart>
</div>
<ol>
    @foreach(var item in DataPoints)
    {
        <li>@item.Time @item.CPU_Usage</li>
    }
</ol>
@code{
    private static Timer timer;
    public string Width { get; set; } = "90%";
    private SfChart liveChart;
    private double dataLength = 100;
    private Random randomNum = new Random();
    private Theme theme { get; set; }
    public ObservableCollection<ChartDataPoint> DataPoints;
    static void list_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
        {            //为了不阻止主线程Add,事件用 “工作线程”处理
            Task.Factory.StartNew((o) =>
            {
                var obj = o as NotifyCollectionChangedEventArgs;
                switch (obj.Action)
                {
                    case NotifyCollectionChangedAction.Add:
                        Console.WriteLine($"{ DateTime.Now.ToString( "yyyy-MM-dd  HH:mm:ss ffff")} 当前线程:{Thread.CurrentThread.ManagedThreadId:d2}, 操作方法:{obj.Action}");
                        break;
                    case NotifyCollectionChangedAction.Move:
                        Console.WriteLine($"{ DateTime.Now.ToString( "yyyy-MM-dd  HH:mm:ss ffff")} 当前线程:{Thread.CurrentThread.ManagedThreadId:d2}, 操作方法:{obj.Action}");
                        break;
                    case NotifyCollectionChangedAction.Remove:
                        Console.WriteLine($"{ DateTime.Now.ToString( "yyyy-MM-dd  HH:mm:ss ffff")} 当前线程:{Thread.CurrentThread.ManagedThreadId:d2}, 操作方法:{obj.Action}");
                        break;
                    case NotifyCollectionChangedAction.Replace:
                        Console.WriteLine($"{ DateTime.Now.ToString( "yyyy-MM-dd  HH:mm:ss ffff")} 当前线程:{Thread.CurrentThread.ManagedThreadId:d2}, 操作方法:{obj.Action}");
                        break;
                    case NotifyCollectionChangedAction.Reset:
                        Console.WriteLine($"{ DateTime.Now.ToString( "yyyy-MM-dd  HH:mm:ss ffff")} 当前线程:{Thread.CurrentThread.ManagedThreadId:d2}, 操作方法:{obj.Action}");
                        break;
                    default:
                        break;
                }
                Thread.Sleep(50);
            }, e);             
        }
    protected override void OnInitialized()
    {
        // Provide the chart with initial data during page load.
        DataPoints = new ObservableCollection<ChartDataPoint>();
            DataPoints.CollectionChanged   = list_CollectionChanged;  
        for (int i = 0; i < dataLength; i  )
            DataPoints.Add(new ChartDataPoint
            {
                Time = DateTime.Now.AddSeconds(i-dataLength),
                CPU_Usage = randomNum.Next(30, 80)
            });
        // Starting live update in the chart.
        timer = new Timer(500);
        timer.Elapsed  = AddData;
        timer.AutoReset = true;
        timer.Enabled = true;
    }
    protected override void OnAfterRender(bool firstRender)
    {
        base.OnAfterRender(firstRender);
        if(firstRender) {
            
            {
                 Width = "100%";
                 StateHasChanged();
            }
        }
    }
    private void AddData(Object source, ElapsedEventArgs e)
    {
        if (liveChart == null)
            return;
        dataLength  ;
        DataPoints.RemoveAt(0);
        DataPoints.Add(new ChartDataPoint
        {
            Time = DateTime.Now.AddSeconds(0),
            CPU_Usage = randomNum.Next(30, 80)
        });
            InvokeAsync(StateHasChanged);

    }
    public class ChartDataPoint
    {
        public DateTime Time { get; set; }
        public double CPU_Usage { get; set; }
    }
}

知识点:

ObservableCollection<T> 类

表示一个动态数据收集,该集合在添加或删除项或刷新整个列表时提供通知。

事件

CollectionChanged

在添加、删除或移动项或刷新整个列表时发生。

PropertyChanged

在属性值更改时发生。

为当前目录中的项目创建一个依赖框架的跨平台二进制文件:

.NET CLI

代码语言:javascript复制
自 .NET Core 3.0 SDK 起,此示例还为当前平台创建依赖框架的可执行文件。
代码语言:javascript复制
dotnet publish

0 人点赞