How can I set Connection.Closed Event so that it connects again in SignalR?

I want to set a timer in an event disconnected

to automatically try to reconnect.

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 a callback disconnected

:

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

      

But how to do the same using the connection event Closed

in C # (WinForms)?

+3


source to share


1 answer


Please take it as pseudocode, I cannot test it and it cannot compile, but it should give you an idea of ​​the direction you should take and you can fix potential flaws:

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 more of a timer-related question than a SignalR question, so you can find several answer questions about Timer

(there is more than one type) that should help you understand this code, tweak the details and deal with nuances such as threading issues. and etc.

+1


source







All Articles