完全在 Blazor Webassembly 中完成的 setInterval 的有效替代方案是什么?



我在想:

protected override async Task OnInitializedAsync() {
//...
RunMeEndlesslyWithoutAwait();
//...
}
protected async Task RunMeEndlesslyWithoutAwait() {
while (online) {
//... do stuff
await Task.Delay(60000);
}
}

但我不确定这是否是最合适的。

是否有任何已知的最佳/有效的方法来使用blazor webassembly的JS函数setInterval(...)?

您可能正在寻找Timer

@using System.Timers
@code
{
Timer timer = new Timer();
protected override Task OnInitializedAsync()
{
timer.Interval = 6000;
timer.Elapsed +=async(_, _) => await RunMeEndlesslyWithoutAwait();
}
}

如果使用PeriodicTimer会更好,因为它是创建后台任务的新方法。

请注意,它可以在。net 6中使用。

下面是一个用法示例:

public class BackgroundTask
{
private Task? _timerTask;
private readonly PeriodicTimer _timer;
private readonly CancellationTokenSource _cts= new();
public BackgroundTask(TimeSpan interval)
{
_timer = new(interval);
}
public void Start()
{
_timerTask = RunAsync();
}
private async Task RunAsync()
{
try
{
while (await _timer.WaitForNextTickAsync(_cts.Token))
{
Console.WriteLine($"Task worked: {DateTime.Now:O}");
}
}
catch (OperationCanceledException)
{
}
}
public async Task StopAsync()
{
if (_timerTask is null)
{
return;
}
_cts.Cancel();
await _timerTask;
_cts.Dispose();
Console.WriteLine("Task has just been stopped.");
}

你这样称呼它:

BackgroundTask task = new BackgroundTask(TimeSpan.FromSeconds(1));
task.Start();

最新更新