fingers10
fingers10

Reputation: 7927

Calling StateHasChanged() every second is optimal in blazor web assembly?

I'm developing a blazor webassembly app. I have the requirement to show current DateTime in my app. Here is how I achieved my requirement with pure C#.

@using System.Threading

<p>@CurrentDateTime</p>

@code {
    protected override void OnAfterRender(bool firstRender)
    {
        if (firstRender)
        {
            new Timer(DateTimeCallback, null, TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(1));
        }
    }

    private void DateTimeCallback(object state)
    {
        CurrentDateTime = DateTimeOffset.UtcNow.ToString("dd MMM yyyy hh:mm:ss tt");
        StateHasChanged();
    }
}

This gives the exact current time and gets updated every second. But I'm little bit worried on calling StateHasChanged() every second. Does it impact performance in long run? or I need to fallback to javascript to achieve this functionality? Please suggest your inputs.

Upvotes: 6

Views: 1887

Answers (1)

Henk Holterman
Henk Holterman

Reputation: 273169

But I'm little bit worried on calling StateHasChanged() every second.

Don't be. Every millisecond might be a problem, every second should be fine.

Some improvements:

  1. System.Threading.Timer is IDisposable. You should implement the Dispose logic in this Page. See this answer.

  2. You should make the callback an async void and then await InvokeAsync(StateHasChanged); This makes no difference in WebAssembly at the moment, but one day Blazor/Wasm will get real Threads and then your code will fail. InvokeAsync() is already required for Blazor/server.

Upvotes: 5

Related Questions