2014-02-10 26 views
0

我有一個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()方法返回時沒有錯誤並且連接狀態。如果您想要執行某些操作或重試連接,則必須檢查連接的狀態。

+0

您正在運行什麼版本的SignalR服務器和.Net客戶端? – halter73

+0

對不起,應該提到它。服務器和客戶端在v2.0中。 –

回答

0

從Connection.Start收到的任務很可能會因爲超時而不是故障而被取消。這應該是一個簡單的辦法:

this.connection.Start().ContinueWith(task => 
{ 
    if (task.IsFaulted || task.IsCanceled) 
    { 
     this.OnRaiseServerConnectionClosedEvent(); 
    } 
    else 
    { 
     this.JoinGroup(); 
     this.StopTimer(); 
     this.OnRaiseServerConnectionOpenedEvent(); 
    } 
}); 

如果使用wait()的,而不是ContinueWith,當任務被取消包含在其InnerExceptions收集的OperationCanceledException的AggregateException將被拋出。

+0

添加「task.IsCanceled」沒有修復它,即使我的服務器關閉,else塊仍然執行。使用Wait()我有效地得到了AggregateException,但由於JoinGroup()方法中的Invoke,我也得到了InvalidOperationException。 –