1 回答
TA贡献2011条经验 获得超2个赞
您可以创建一个可以在多种情况下为您服务的计时器服务:
创建服务类:
public class BlazorTimer
{
private Timer _timer;
internal void SetTimer(double interval)
{
_timer = new Timer(interval);
_timer.Elapsed += NotifyTimerElapsed;
_timer.Enabled = true;
_timer.Start();
}
private void NotifyTimerElapsed(object sender, ElapsedEventArgs e)
{
OnElapsed?.Invoke();
}
public event Action OnElapsed;
}
在 Program.Main 方法中将服务作为瞬态添加到 DI 容器:
builder.Services.AddTransient(config =>
{
var blazorTimer = new BlazorTimer();
blazorTimer.SetTimer(1000);
return blazorTimer;
});
用法
@page "/"
@implements IDisposable
@inject BlazorTimer Timer
@count.ToString()
@code{
private int count = 0;
protected override void OnInitialized()
{
Timer.OnElapsed += NotifyTimerElapsed;
base.OnInitialized();
}
private void NotifyTimerElapsed()
{
// Note: WebAssembly Apps are currently supporting a single thread, which
// is why you don't have to call
// the StateHasChanged method from within the InvokeAsync method. But it
// is a good practice to do so in consideration of future changes, such as
// ability to run WebAssembly Apps in more than one thread.
InvokeAsync(() => { count++; StateHasChanged(); });
}
public void Dispose()
{
Timer.OnElapsed -= NotifyTimerElapsed;
}
}
添加回答
举报