Reputation: 7927
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
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:
System.Threading.Timer is IDisposable. You should implement the Dispose logic in this Page. See this answer.
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