如何设置Connection.Closed事件以使其在SignalR中重新连接?

时间:2015-05-18 02:53:29

标签: c# signalr signalr.client

我想在disconnected事件上设置一个Timer来自动尝试重新连接。

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?

我只知道如何使用disconnected回调在Javascript中设置它:

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

但是如何使用C#(WinForms)中的连接Closed事件来做同样的事情?

1 个答案:

答案 0 :(得分:1)

请将其作为代码,我无法真正测试它并且可能无法编译,但它应该让您了解要采取的方向,并且您应该能够修复潜在的缺陷:

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();

这实际上是一个与计时器相关的问题,而不是SignalR问题,就此而言,您可以找到关于Timer的{​​{3}} several answered(还有更多信息)一种类型)应该帮助您理解这些代码,调整细节并与线程问题等细微差别作斗争。