Ivan-Mark Debono
Ivan-Mark Debono

Reputation: 16310

How to check if the last automatic reconnect was completed?

I'm creating a hub client as follows:

hub = new HubConnectionBuilder()
    .WithUrl(Constants.HubsUrl + "/MainHub", options =>
    {
        options.Headers.Add(Constants.HeaderToken, token);
        options.UseDefaultCredentials = true;
    })
    .ConfigureLogging(logging =>
    {
        logging.AddDebug();
        logging.SetMinimumLevel(Microsoft.Extensions.Logging.LogLevel.Warning);
    })
    .WithAutomaticReconnect(new[] { 
        TimeSpan.Zero, 
        TimeSpan.FromSeconds(5), 
        TimeSpan.FromSeconds(30),
        TimeSpan.FromMinutes(1),
        TimeSpan.FromMinutes(5)
    })
    .Build();

hub.Closed += (exception) =>
{
    Closed?.Invoke(this, new EventArgs());

    if (exception == null)
    {
        Console.WriteLine("Connection closed without error.");
    }
    else
    {
        Console.WriteLine($"Connection closed due to an error: {exception}");
    }

    return Task.CompletedTask;
}; 

This is all good.

However I would like to know if the last reconnect attempt was completed so that I can show a message to the user.

Do I need to do it the old-fashioned way with a counter or is there a better solution?

Upvotes: 1

Views: 207

Answers (1)

Sebastian Grunow
Sebastian Grunow

Reputation: 104

On your hub you have the Reconnected event.

Just attach to it and do your notification from within there. So additionally to your hub.Closed += [...], you would have something in the likes of:

hub.Reconnected += (connectionId) => Console.WriteLine($"Successfully reconnected. ({connectionId})");

If you also want to display, that a reconnection is being attempted, you have the Reconnecting event available.

Upvotes: 1

Related Questions