wtf512
wtf512

Reputation: 4738

How to set Connection.Closed Event to make it reconnect in SignalR?

I want to set a Timer on the disconnected event to automatically attempt reconnection.

var querystringData = new Dictionary<string, string>();
querystringData.Add("uid", Uid);
var connection = new HubConnection(HubUri, querystringData);
_hub = connection.CreateHubProxy(HubName);
connection.Start(new LongPollingTransport()).Wait();
connection.Closed += ???; //how to set this event to try to reconnect?

I only know how to set it in Javascript with the disconnected callback:

$.connection.hub.disconnected(function() {
   setTimeout(function() {
       $.connection.hub.start();
   }, 5000); // Restart connection after 5 seconds.
});

But how to do the same using the connection's Closed event in C# (WinForms)?

Upvotes: 3

Views: 2728

Answers (1)

Wasp
Wasp

Reputation: 3425

Please take it as pseudo code, I cannot really test it and it might not compile, but it should give you an idea about the direction to take and you should be able to fix potential defects:

using System.Windows.Forms;

//...your stuff about query string...
_hub = connection.CreateHubProxy(HubName);

//quick helper to avoid repeating the connection starting code
var connect = new Action(() => 
{
    connection.Start(new LongPollingTransport()).Wait();
});

Timer t = new Timer();
t.Interval = 5000;
t.Tick += (s, e) =>
{
    t.Stop();
    connect();
}

connection.Closed += (s, e) => 
{
    t.Start(); 
}

connect();

This is actually more a timer-related question than a SignalR question, on that regard you can find several answered questions about Timers (there are more then one type) that should help you with understanding this code, adjusting details and fighting with nuances like threading issues etc.

Upvotes: 1

Related Questions