C# 如何以特定的间隔更新动态DOM值?
我需要使用每秒的计时器动态更新DOM值 我试过每秒钟增加一个计数器值。但是在那段代码中,我只得到了DOM值的最终值。我需要DOM中的每一秒值C# 如何以特定的间隔更新动态DOM值?,c#,asp.net-core,blazor,C#,Asp.net Core,Blazor,我需要使用每秒的计时器动态更新DOM值 我试过每秒钟增加一个计数器值。但是在那段代码中,我只得到了DOM值的最终值。我需要DOM中的每一秒值 <h1>Counter</h1> <p>Current count: @currentCount</p> <button class="btn btn-primary" @onclick="StartLiveUpdate">Click me</button> <button
<h1>Counter</h1>
<p>Current count: @currentCount</p>
<button class="btn btn-primary" @onclick="StartLiveUpdate">Click me</button>
<button class="btn btn-primary" @onclick="StopLiveUpdate">Stop</button>
@code {
private static System.Timers.Timer syncTimer;
Random random = new Random();
void StartLiveUpdate()
{
syncTimer = new System.Timers.Timer(1000);
syncTimer.Elapsed += IncrementCount;
syncTimer.AutoReset = true;
syncTimer.Enabled = true;
}
void StopLiveUpdate()
{
syncTimer.Enabled = false;
syncTimer.Stop();
}
int currentCount = 0;
void IncrementCount(Object source, System.Timers.ElapsedEventArgs e)
{
currentCount++;
this.StateHasChanged();
}
}
计数器
当前计数:@currentCount
点击我
停止
@代码{
专用静态系统。定时器。定时器同步定时器;
随机=新随机();
void startiveupdate()
{
syncTimer=新系统计时器计时器计时器(1000);
syncTimer.Appead+=递增计数;
syncTimer.AutoReset=true;
syncTimer.Enabled=true;
}
void StopLiveUpdate()
{
syncTimer.Enabled=false;
syncTimer.Stop();
}
int currentCount=0;
无效增量计数(对象源,System.Timers.ElapsedEventArgs e)
{
currentCount++;
此.StateHasChanged();
}
}
运行上述代码时,我会在IncrementCount函数中引发以下异常:
System.InvalidOperationException:'当前线程未与调度程序关联。在触发呈现或组件状态时,使用InvokeAsync()将执行切换到调度程序
将StateHasChanged调用传递给InvokeAsync可以解决以下问题:
InvokeAsync(this.StateHasChanged);
替换您的this.StateHasChanged();与答案的最后一行对齐-在递增计数函数中,您是否愿意接受答案,它对您有效?