Want to try a multi-user demo?
Make sure to open the page in multiple browsers, click on a book and hit Save. You will see the change simultaneous in each browser.
Using SignalR for real time data updates
However both these approaches have one fundamental problem. When a user requests some data he has a local copy of that in the browser. If another user now updates that same entity on the server the first user still has the old stale data in front of him. And that will remain so until reloads the data. Of course we can add some code to actively check for changes to the data but usually there will be no change so that results in a lot of useless network traffic.
Replacing a REST service with SignalR
Suppose the client doesn’t load the data using a REST service but uses SignalR instead. Doing request/response asynchronous style communication with SignalR is easy, a little different from using jQuery but no big difference. In the following code the clients starts the communications hub and passed the loadBooks callback to load the books as soon as the communications are initialized.
The C# code on the server is no big deal either and hardly any more complex then the previous chat application.
Push notifications after updates
So far we have not achieved much, the user will still be looking at stale data when the data on the server is updated by another user. But SignalR uses persistent connections and can easily push changes to each connected client when that happens. All we need to do is add a bit of client side code to send updates and handle the change notifications.
Supporting this on the server using a SignalR hub is easy. Below is the complete C# source code for the hub that servers up data, accepts updates and inserts and broadcasts those updates and inserts to all connected clients.
With this addition each user is automatically notified of any change anyone makes and will see the data in the browser update dynamically. For some extra effects I have added a small jQuery animation to the record being updated on the client.