2014-02-10 23 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。 –