我有一個C#SignalR客戶端,並且希望在連接到我的服務器時成功/失敗時執行一些操作。這裏是我的代碼:即使連接不可能,SignalR Start()的任務仍在繼續
this.connection.Start().ContinueWith(task =>
{
if (task.IsFaulted)
{
this.OnRaiseServerConnectionClosedEvent();
}
else
{
this.JoinGroup();
this.StopTimer();
this.OnRaiseServerConnectionOpenedEvent();
}
});
}
else塊總是執行,不關心,如果一臺服務器在不在......
我也試圖與坐等或與等待(),但同樣的情況。
我明白.net任務正確,我認爲但在這裏我卡住了。
您的幫助將不勝感激:)
晏
編輯:
現在我的代碼看起來像
try
{
this.connection.Start().Wait();
if (this.connection.State == ConnectionState.Connected)
{
this.JoinGroup();
this.StopTimer();
this.OnRaiseServerConnectionOpenedEvent();
}
}
catch (AggregateException)
{
this.OnRaiseServerConnectionClosedEvent();
}
catch (InvalidOperationException)
{
this.OnRaiseServerConnectionClosedEvent();
}
如果沒有服務器存在,任務的創建Start()方法返回時沒有錯誤並且連接狀態。如果您想要執行某些操作或重試連接,則必須檢查連接的狀態。
您正在運行什麼版本的SignalR服務器和.Net客戶端? – halter73
對不起,應該提到它。服務器和客戶端在v2.0中。 –