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:
Default behavior:
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:
Custom IRetryPolicy
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())