20行程式碼寫一個簡單 Blazor 時鐘元件

AlexChow發表於2024-05-16

群裡有些同學詢問怎麼實現定時重新整理介面, 那咱們寫點試試看能不能達到需求.

程式碼比較簡單, 就是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 />

相關文章