Today, when I was “mind-coding”, i.e. writing applications in my head (which I tend to do pretty often actually), I started building a Blazor application that shared data across multiple clients. In a Blazor Server application, all data modifications happen on the server. Data then gets sent back to the client over a SignalR connection. Normally, the data on the server changes in response to an action that the user takes. For instance clicking a button or typing in some text in a text box. But that does not have to be the case. The trigger to change the data on the server might just as well come from outside of the application.

So I had to try this out in practice as well, and not just in theory. That’s why I created this sample application on my GitHub account. this article describes the main points of that application.

The Blazor Timer Application

The sample timer application is dead-simple. The main purpose is just to show you the concept of sharing data across multiple clients. You start it on one client, and the time starts ticking on all clients currently on the page.

The concept works. I’ve deployed the application to Azure, and tried running it simultaneously on my laptop and mobile phone. The changes occur in real-time on all clients.

The magic happens in the Timer.razor page and its code-behind file Timer.razor.cs. When the start button in the UI is clicked, it calls the StartAsync() method in the code-behind class. This method starts the timer instance defined by the class. The timer is triggered every second. Each time the static counter SharedTotalSeconds is incremented. In addition, the static OnTimerChanged event is also triggered to signal all connected clients that the timer has been updated. The rest is then just normal event handling where the value displayed in the timer is calculated from the total number of seconds.

Real-World Scenario

Obviously, you need to implement this in a bit more robust fashion for production use. But the concept is still the same. You update a shared data source such as a database or table. Then you trigger an event that gets delivered to every connected client. Each client then updates their own state from the shared information

You can probably think of lots of different use cases for this, ranging from chat applications to real-time scoreboards and monitoring applications. I already have a few ideas where I’m going build on this pattern, but more about those in a future article. Have fun!


0 Comments

Leave a Reply

Your email address will not be published. Required fields are marked *