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.