Reputation: 13886
We have been facing issues with reconnection in Signalr .Net Core, what are the best practices for reconnecting to signalr- hub?
Following seem to be most respected article on reconnecting. But seems outdated, isn't it? Best practice for reconnecting SignalR 2.0 .NET client to server hub
Upvotes: 6
Views: 6040
Reputation: 1001
The best way to do this "reconnecting" is with the WithAutomaticReconnect
method.
So instead of writing your own reconnection logic, you can use the built in one.
First things first, you would have to remove your current reconnection logic, and add .WithAutomaticReconnect()
to your HubConnectionBuilder
.
Now you have two options:
The default values for this method are TimeSpan[0, 2000, 10000, 30000, null]
, meaning that it will wait X (0, 2, 10, 30) seconds after each failed attempt to try reconnecting again. Once it reaches null
, it will stop trying.
You can customize this array, but it will always have a null at the end, which makes it unreliable if you want it to try infinitely. Which brings us to the next option:
An IRetryPolicy
indicates how many seconds the HubConnectionBuilder
has to wait after each failed attempt to try reconnecting again.
This method runs infinitely until the connection is restored.
To implement a custom IRetryPolicy
:
public class RetryPolicyLoop : IRetryPolicy
{
private const int ReconnectionWaitSeconds = 5;
public TimeSpan? NextRetryDelay(RetryContext retryContext)
{
return TimeSpan.FromSeconds(ReconnectionWaitSeconds);
}
}
So this is how it would look like in your HubConnectionBuilder
:
.WithAutomaticReconnect(new RetryPolicyLoop())
Upvotes: 17
Reputation: 1931
Currently you have to write your own reconnection logic. The docs have examples of how to do a naive reconnect for Javascript client and .NET client.
Upvotes: 3
Reputation: 1439
(Your link is referencing the .NET (4.x) client / version of SignalR, not the .NET CORE version. It's not outdated. They are distinctly different in many aspects and the are not compatible with each other. You must use a .NET CORE hub with a .NET CORE client, you cannot mix these with the older .NET (4.x) hub or client.
According to this issue back in 2017, which is still open as of this post, David Fowler said "We're looking at adding the automatic reconnect functionality back to SignalR in the next preview release."
So, depending on what version you are at and where this issue stands, you need to follow up with that project.
https://github.com/aspnet/AspNetCore/issues/5282
Upvotes: 0