Eugene
Eugene

Reputation: 277

What's the efficient alternative to setInterval done completely in Blazor Webassembly?

I was thinking of something like:

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

but I'm not sure if it's the most adeguage.

Is there any known best/efficient ways to the JS function setInterval(...) that uses blazor webassembly?

Upvotes: 0

Views: 2399

Answers (2)

mehmetbilen
mehmetbilen

Reputation: 41

It would be better if you use PeriodicTimer as it is new and fancy way to create a backgroud task.

Please note that it is available with .NET 6.

Here is a sample of usage:

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.");
    }

You call it like this:

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

Upvotes: 2

Alamakanambra
Alamakanambra

Reputation: 7826

You are probably looking for a Timer

@using System.Timers

@code
{
  Timer timer = new Timer();

  protected override Task OnInitializedAsync()
    {
        timer.Interval = 6000;
        timer.Elapsed +=async(_, _) => await RunMeEndlesslyWithoutAwait();
    }
}

Upvotes: 5

Related Questions