Maui Blazor 中文社区 QQ群:645660665

20行代码写一个简单 Blazor 时钟组件

群里有些同学询问怎么实现定时刷新界面, 那咱们写点试试看能不能达到需求.

代码比较简单, 就是Task每秒刷新页面. 然后封装为组件实现只局部刷新.

Demo

TimerAme.razor

<p>@Label @DateTime.Now.ToLongTimeString()</p>

TimerAme.razor.cs

using Microsoft.AspNetCore.Components;

public partial class TimerAme : ComponentBase, IDisposable
{
    [Parameter]
    public string Label { get; set; } = "时间:";

    private CancellationTokenSource? AutoRefreshCancelTokenSource { get; set; }

    protected override void OnInitialized() => worker();

    /// <summary>
    /// Dispose 方法
    /// </summary>
    public void Dispose() => AutoRefreshCancelTokenSource = null;

    public void worker()
    {
        AutoRefreshCancelTokenSource = new CancellationTokenSource();
        _ = Task.Run(async () =>
        {
            try
            {
                while (!(AutoRefreshCancelTokenSource?.IsCancellationRequested ?? true))
                {
                    await InvokeAsync(StateHasChanged);
                    await Task.Delay(TimeSpan.FromSeconds(1), AutoRefreshCancelTokenSource?.Token ?? new CancellationToken(true));
                }
            }
            catch (TaskCanceledException) { }
        });

    }
}

使用组件

<TimerAme />
posted @ 2024-05-16 07:20  AlexChow  阅读(1128)  评论(0编辑  收藏  举报