2015-05-18 36 views
2

我想在disconnected事件上設置一個Timer來自動嘗試重新連接。如何設置Connection.Closed事件以使其在SignalR中重新連接?

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事件做?

回答

0

請把它作爲代碼,我真的不能測試它,它可能無法編譯,但它應該給你方向的主意,採取,你應該能夠解決潛在的缺陷:

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問題的定時器相關問題,在這方面你可以找到severalansweredquestionsTimer秒(有多於一個類型)應該幫助你理解這個代碼,調整細節和戰鬥細微差別像線程問題等。

相關問題