Skip to content

Instantly share code, notes, and snippets.

@UweKeim
Last active January 28, 2024 21:30
Show Gist options
  • Save UweKeim/eccd798a2d6c07c6793beb3b2c95b096 to your computer and use it in GitHub Desktop.
Save UweKeim/eccd798a2d6c07c6793beb3b2c95b096 to your computer and use it in GitHub Desktop.
Timer in Blazor 3.1
namespace ZetaHelpdesk.MainBlazor.Code.Components
{
using System;
using System.Timers;
// https://wellsb.com/csharp/aspnet/blazor-timer-navigate-programmatically/
public sealed class BlazorTimer
{
private Timer _timer;
public void SetTimer(double intervalMilliseconds, bool repeat)
{
_timer = new Timer(intervalMilliseconds);
_timer.Elapsed += NotifyTimerElapsed;
_timer.AutoReset = repeat;
_timer.Enabled = true;
}
public event Action OnElapsed;
private void NotifyTimerElapsed(object source, ElapsedEventArgs e)
{
OnElapsed?.Invoke();
if (!_timer.AutoReset)
{
_timer.Stop();
_timer.Dispose();
_timer = null;
}
}
}
}
// This files is a code-behind file for a Blazor component and demonstrates
// the usage of the BlazorTimer component.
namespace ZetaHelpdesk.MainBlazor.Shared
{
using Code.Components;
using Microsoft.AspNetCore.Components;
using RuntimeCore.Services;
using System.Threading.Tasks;
public partial class InboxCountBadge
{
[Inject] public IAppRepositories AppRepositories { get; set; }
[Inject] public BlazorTimer Timer { get; set; }
private int Count;
protected override async Task OnInitializedAsync()
{
await refreshCount();
await startTimer();
}
// https://blazor-tutorial.net/refresh-ui-manually
private const double intervalMilliseconds = 5000;
private async Task startTimer()
{
Timer.SetTimer(intervalMilliseconds, true);
Timer.OnElapsed +=
async delegate
{
await refreshCount();
};
}
private async Task refreshCount()
{
var before = Count;
var after = await AppRepositories.Ticket.CountAllInboxTickets();
if (after != before)
{
Count = after;
await InvokeAsync(StateHasChanged);
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment