Last active
January 28, 2024 21:30
-
-
Save UweKeim/eccd798a2d6c07c6793beb3b2c95b096 to your computer and use it in GitHub Desktop.
Timer in Blazor 3.1
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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