Skip to content

Commit

Permalink
The most significant changes include the addition of the `System.Time…
Browse files Browse the repository at this point in the history
…rs` namespace to use the `Timer` class, the introduction of a `Timer` object that ticks every second, and the creation of a `TimerElapsed` method that triggers every time the timer ticks. Additionally, the HTML markup for the counter display and button has been removed, and a `Dispose` method has been added to clean up the timer when the component is disposed.

1. The `System.Timers` namespace has been added to the file to use the `Timer` class. This allows the use of a timer in the code.
2. A `PageTitle` has been added to the `@page` directive, providing a title for the webpage.
3. The HTML markup for the counter display and button has been removed, simplifying the user interface.
4. A `Timer` object has been added to the code block, initialized in the `OnInitialized` method. The timer is set to tick every 1 second (1000 milliseconds), auto-reset, and start immediately.
5. A `TimerElapsed` method has been added, which is triggered every time the timer ticks. This method calls the `IncrementCount` method and then invokes `StateHasChanged` to re-render the component on the UI thread.
6. A comment has been added to the `IncrementCount` method to explain that it increments the counter, providing clarity for future code maintenance.
7. A `Dispose` method has been added to clean up the timer when the component is disposed, ensuring efficient resource management.
  • Loading branch information
Raj committed May 12, 2024
1 parent 35f6d9a commit 5ee6f59
Showing 1 changed file with 24 additions and 6 deletions.
30 changes: 24 additions & 6 deletions src/AspNet.Core.Blazor.WebAssembly/Pages/Counter.razor
Original file line number Diff line number Diff line change
@@ -1,18 +1,36 @@
@page "/counter"

@using System.Timers;
@page "/counter"
<PageTitle>Counter</PageTitle>

<h1>Counter</h1>

<p role="status">Current count: <FluentBadge Appearance="Appearance.Neutral">@currentCount</FluentBadge></p>

<FluentButton Appearance="Appearance.Accent" @onclick="IncrementCount">Click me</FluentButton>

@code {
private int currentCount = 0;
private Timer timer = new Timer();

protected override void OnInitialized()
{
timer = new Timer(1000); // Set the timer to tick every 1000 milliseconds (1 second)
timer.Elapsed += TimerElapsed;
timer.AutoReset = true; // Continue the timer in a loop
timer.Enabled = true; // Start the timer
}

private void TimerElapsed(object? sender, System.Timers.ElapsedEventArgs e)
{
IncrementCount();
InvokeAsync(StateHasChanged); // Re-render the component on the UI thread
}

private void IncrementCount()
{
currentCount++;
currentCount++; // Increment the counter
}

public void Dispose()
{
timer?.Dispose(); // Clean up the timer when the component is disposed
}
}

0 comments on commit 5ee6f59

Please sign in to comment.