6

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.

fingers10
  • 6,675
  • 10
  • 49
  • 87

1 Answers1

5

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.

H H
  • 263,252
  • 30
  • 330
  • 514
  • Is there any reason to go for `async void` instead of `async Task`? – Joost00719 Oct 19 '22 at 07:48
  • 1
    The timer doesn't support `async Task`. So use either an `async void` (Ok-ish for events) or do __not__ `await` the InvokeAsync(). Whatever. – H H Oct 19 '22 at 08:29
  • For an in-depth discussion, in Microsoft's docs, see [Receiving a call from something external to the Blazor rendering and event handling system](https://learn.microsoft.com/en-us/aspnet/core/blazor/components/rendering?view=aspnetcore-7.0#receiving-a-call-from-something-external-to-the-blazor-rendering-and-event-handling-system). – DavidRR Jun 02 '23 at 13:29