Blazor:如何开始随时间循环?示例 - 2 分钟后生成一个问题

2 c# asp.net-core blazor blazor-server-side

我有 10 个问题,有多个答案。我想每 2 分钟后生成一个新问题。并且还向用户显示每个问题的时间。我怎样才能实现这个目标?

我无法显示时间

<div>
    <h2> Time left : @*Here I want to show Time*@ </h2>
</div>

<div class="row">
    @if (id != 0)
    {
         @*This is Question Component & Here I pass the Question id *@
        <QuestionCard Id="@id.ToString()"></QuestionCard>
    }
    else
    {
        <MatH1>Loading . . . . .</MatH1>
    }
</div>


@code {


    System.Timers.Timer aTimer = new System.Timers.Timer();
    private int id { get; set; } = 0;
    protected override async Task OnInitializedAsync()
    {
        await Task.Run(() => Start());

    }
    void Start()
    {
        //aTimer.Elapsed += new ElapsedEventHandler(OnTimedEvent);
        id = 2;  //I Just pass manually Question id
        aTimer.Interval = 5000;
        aTimer.Enabled = true;
        aTimer.Start();
    }
}
Run Code Online (Sandbox Code Playgroud)

我对 Blazor 完全陌生。如有错误请见谅。

小智 5

我这样做是为了向时间展示

<p> @TimeLeft </p>

@code{
    TimeSpan TimeLeft = new TimeSpan(0, 0, 15);
    string displayText = "";

    bool show=false;

    void Start()
    {
        Task.Delay(1000);
        displayText = "Start Time";
        show = true;
        Timer();


    }

    async Task Timer()
    {
        while (TimeLeft > new TimeSpan())
        {
            await Task.Delay(1000);
            TimeLeft = TimeLeft.Subtract(new TimeSpan(0, 0, 1));
            StateHasChanged();
        }


        await AfterTime();
        StateHasChanged();
    }

    Task AfterTime()
    {
        displayText = "Time Expire";
        TimeLeft =  new TimeSpan(0, 0, 15);
        return Task.CompletedTask;
    }
}
Run Code Online (Sandbox Code Playgroud)