3

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

Wasp
  • 3,395
  • 19
  • 37
wtf512
  • 4,487
  • 9
  • 33
  • 55

1 Answers1

1

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.

Community
  • 1
  • 1
Wasp
  • 3,395
  • 19
  • 37