.NET Core SignalR Automatic Reconnects

One of the major differences between old and new .NET Core SignalR is that automatic reconnects are not supported. This means that you need explicitly open a new connection if you lost connection to the server.

I managed to write my own implementation that do automatic reconnects on this new version of .NET Core 2 SignalR that works for me.

The code bellow uses Polly for automatic retry policy and Serilog for logging.

Here is my implementation. Hope someone will find it useful:


var signalRConnection = new HubConnectionBuilder()
     .WithUrl(BaseUrl + "/hubs/integrationserver", options =>
     {
      options.Headers.Add("Authorization", "Basic " + Header);
     }).Build();
signalRConnection.On<string, string>("ReceiveMessage", (entityName, json) =>
{

});


private async void OpenSignalRConnection()
{
var pauseBetweenFailures = TimeSpan.FromSeconds(20);

var retryPolicy = Policy .Handle<Exception>() .WaitAndRetryForeverAsync(i => pauseBetweenFailures , (exception, timeSpan) => { Log.Error(exception.ToString()); }); await retryPolicy.ExecuteAsync(async () => { Log.Information("Trying to connect to SignalR server"); await TryOpenSignalRConnection(); }); }

private async Task<bool> TryOpenSignalRConnection()
{

Log.Information("Starting SignalR connection");

signalRConnection.Closed += SignalRConnection_Closed;

await signalRConnection.StartAsync();
Log.Information("SignalR connection established");
return true;
}


private async Task SignalRConnection_Closed(Exception arg)
{
Log.Information("SignalR connection is closed");

await signalRConnection.StopAsync();

signalRConnection.Closed -= SignalRConnection_Closed;
OpenSignalRConnection();
}

1 Comment on .NET Core SignalR Automatic Reconnects

  1. cristi
    August 23, 2018 at 12:56 pm (3 months ago)

    Looks very good and helpful!

    Reply

Leave a Reply