我有一个非常简单的例子来自标准的Blazor服务器端模板,它展示了即使在调用了StateHasChanged()函数后计时器函数也不会更新UI。
日志输出显示计时器已被触发,如果我等待几秒钟并点击IncrementCount按钮,则计数值会跳转到计时器增加计数器次数的数字。
非常好奇...任何帮助将不胜感激。
敬礼,Stuart
@page "/counter"
@using System.Timers;
@using Microsoft.Extensions.Logging
@inject ILogger<Counter> Logger
<h1>Counter</h1>
<p>Current count: @(currentCount.ToString())</p>
<button class="btn btn-primary" @onclick="IncrementCount">Click me</button>
@code {
private int currentCount = 0;
private void IncrementCount()
{
currentCount++;
}
public System.Timers.Timer timer;
protected override async Task OnInitializedAsync()
{
timer = new Timer(1000);
timer.Elapsed += this.OnTimedEvent;
timer.AutoReset = true;
timer.Enabled = true;
timer.Start();
}
public void OnTimedEvent(Object source, ElapsedEventArgs e)
{
Logger.LogInformation("Timer triggered");
IncrementCount();
StateHasChanged();
}
}