The*_*mer 10 c# system.timers.timer blazor
我是 C# 新手,并尝试使用System.Timer.Timers. 它没有按预期工作,我在互联网上搜索了解决方案,但它并没有真正解决我的问题。我想要的是当用户单击开始按钮时,它开始并显示倒计时。但是虽然计时器有点工作,但当我单击按钮一次时它并没有连续显示计时器,而是我需要多次单击开始按钮才能看到倒计时数字或计时器显示不会改变。这是代码。
@page "/"
<h1>Timer</h1>
<p>@counter</p>
<button @onclick="StartTimer">Start</button>
@code {
private static System.Timers.Timer aTimer;
private int counter = 60;
public void StartTimer()
{
aTimer = new System.Timers.Timer(1000);
aTimer.Elapsed += CountDownTimer;
aTimer.Enabled = true;
}
public void CountDownTimer(Object source, System.Timers.ElapsedEventArgs e)
{
if (counter > 0)
{
counter -= 1;
}
else
{
aTimer.Enabled = false;
}
}
}
Run Code Online (Sandbox Code Playgroud)
Chr*_*lor 16
StateHasChanged()更新计数器时调用,以便更新 UI 元素。
因为您的回调将在单独的线程上运行,所以您需要使用 InvokeAsync 来调用 StateHasChanged()。
public void CountDownTimer(Object source, ElapsedEventArgs e)
{
if (counter > 0)
{
counter -= 1;
}
else
{
aTimer.Enabled = false;
}
InvokeAsync(StateHasChanged);
}
Run Code Online (Sandbox Code Playgroud)