Cover image for [Quick Tip] SignalR — AutoReconnect — Asp.Net Core 3.x

[Quick Tip] SignalR — AutoReconnect — Asp.Net Core 3.x

alemalavasi profile image Alexandre Malavasi ・2 min read

SignalR is one of the most important technologies for creating realtime applications or Web functionalities, such as chats, multi-user application interactions or even online games. The purpose of this article is not to demonstrate fully its use or give so many details but talk a little a bit about one big issue SignalR has (or did have): the connection loss.
To exemplify it, I created a simple Asp.Net Core application, which one is a basic chat using SignalR. That is enough to demonstrate it:

Alt Text

Alt Text

As you probably already know, the SignalR keeps an open connection via Websocket between the client and server, as the following image shows:

Alt Text

At this point, it’s being simulated a chat between two users and what happens if the connection is gone? Exactly like that:

Alt Text

One of the most obvious thing in this kink of application is that we have to be aware that issues could (and will) happen, as connection lost and because of that it is pretty recommendable to create mechanisms for handling this in the frontend, providing minimum information to users on what is going on wrong. But, beyond concerns related to user experience, there are a few involved technical questions and concerns.
Everyone who uses regularly SignalR in many projects knows that make reconnection in SignalR without making “tricks” in the code is something not so easy to do depends on the scenario and complexity.
Thinking on that, together with many improvements on .NET Core 3.0, in general, the big update contains new implementations for SignalR as well, since its 6th Preview.

Alt Text

In my opinion, one of the most relevant of that is a method to manage the reconnection between the client and server in case of server issues, instability, unavailability, etc.

Alt Text

As you can see in the image above, there is now an extension method called “WithAutomaticReconnect”, which allows you to configure the intervals that the client will try to reconnect with the server. The default unit is in milliseconds and in the example, I’ve set it to attempt the reconnection after 1 second, 5 seconds, etc. In case you want to stop the attempts, just specify a null value, like I did, indicating to the method that it should finish.
To simulate the connection issue on local, I stopped the application on the local server and, automatically, I started to receive connection error messages. But, after about three seconds I reactivated the server and the connection was established again, successfully.

Alt Text

I hope this quick and simple article had helped a little a bit. Thank you for reading it.

Posted on by:

alemalavasi profile

Alexandre Malavasi


MCP | MCTS | MCPD | ITIL | .NET | MBA | MTAC | Technical Leader | Consultant | .NET Developer


markdown guide