Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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)?

like image 916
wtf512 Avatar asked Dec 12 '25 22:12

wtf512


1 Answers

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.

like image 63
Wasp Avatar answered Dec 15 '25 11:12

Wasp



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!