Skip to content

Instantly share code, notes, and snippets.

@conficient
Last active June 22, 2021 08:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save conficient/63ae41ca344a1659b2d900d6ce5d7c60 to your computer and use it in GitHub Desktop.
Save conficient/63ae41ca344a1659b2d900d6ce5d7c60 to your computer and use it in GitHub Desktop.
Shared counter sample

Shared Counter sample for Blazor Server

This gist shows a shared CounterService that can be used on a basic Blazor Server website. The counter instance is a singleton service on the service (declared in Startup.cs using services.AddSingleton<CounterService>();).

You can replace the code in Counter.razor as shown and now you have a counter that everyone can click and it increments and updates across all users.

The CounterService.cs uses Interlocked.Increment(ref _count); to update to ensure updates to _count are thread-safe as multiple clients might try to increment at the same time.

@page "/counter"
@inject CounterService counterService
@implements IDisposable
<h1>Counter</h1>
<p>Current count: @counterService.Count</p>
<button class="btn btn-primary" @onclick="IncrementCount">Click me</button>
@code {
protected override void OnInitialized()
{
// listen for events - call StateHasChanged if one occurs
counterService.OnChange += ()=>
{
// we have to use InvokeAsync as the service may be on a different thread
InvokeAsync(StateHasChanged);
};
}
// click event: tell the service to increment
private void IncrementCount()
{
counterService.Increment();
}
public void Dispose()
{
// remove event on close
counterService.OnChange -= StateHasChanged;
}
}
// Injectable service for the shared counter
// Add services.AddSingleton<CounterService>(); in Startup.cs
public class CounterService
{
public void Increment()
{
// increment in thread-safe way
Interlocked.Increment(ref _count);
NotifyStateChanged();
}
private int _count = 0;
public int Count => _count;
// this method hides the OnChange to simplify it
private void NotifyStateChanged() => OnChange?.Invoke();
// event for change notification
public event Action OnChange; // event for changes
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment