Signalr 信号机启动();即使无法连接,s的任务仍在继续

Signalr 信号机启动();即使无法连接,s的任务仍在继续,signalr,Signalr,我有一个C#Signal客户端,我想在连接到服务器成功/失败时执行一些操作。这是我的密码: this.connection.Start().ContinueWith(任务=> { if(task.IsFaulted) { this.OnRaiseServerConnectionClosedEvent(); } 其他的 { 这是JoinGroup(); 这个.StopTimer(); this.onRaiseServerConnectionOpenEvent(); } }); } else块总是

我有一个C#Signal客户端,我想在连接到服务器成功/失败时执行一些操作。这是我的密码:

this.connection.Start().ContinueWith(任务=>
{
if(task.IsFaulted)
{
this.OnRaiseServerConnectionClosedEvent();
}
其他的
{
这是JoinGroup();
这个.StopTimer();
this.onRaiseServerConnectionOpenEvent();
}
});
}
else块总是被执行,不管服务器是否在这里

我也尝试过使用Wait或
Wait()
,但情况相同

我想我对.net任务的理解是正确的,但在这里我被卡住了


现在我的代码看起来像

试试看
{
this.connection.Start().Wait();
if(this.connection.State==ConnectionState.Connected)
{
这是JoinGroup();
这个.StopTimer();
this.onRaiseServerConnectionOpenEvent();
}
}
捕获(聚合异常)
{
this.OnRaiseServerConnectionClosedEvent();
}
捕获(无效操作异常)
{
this.OnRaiseServerConnectionClosedEvent();
}

当不存在服务器时,由Start()方法创建的任务将返回,且状态为“正在连接”。如果要执行某些操作或重试连接,则必须检查连接状态。

您从连接接收的任务。启动可能由于超时而取消,而不是出现故障。这应该是一个简单的解决方案:

this.connection.Start().ContinueWith(任务=>
{
if(task.IsFaulted | | task.IsCanceled)
{
this.OnRaiseServerConnectionClosedEvent();
}
其他的
{
这是JoinGroup();
这个.StopTimer();
this.onRaiseServerConnectionOpenEvent();
}
});

如果您使用Wait()而不是ContinueWith,则在取消任务时,将抛出在其InnerExceptions集合中包含OperationCanceledException的AggregateException。

您运行的是什么版本的SignalR server和.Net client?抱歉,应该提到它。服务器和客户端都在v2.0中。添加“task.IsCanceled”无法修复此问题,即使我的服务器关闭,else块仍会执行。使用Wait()我有效地获得了AggregateException,但由于JoinGroup()方法中的调用,我还获得了InvalidOperationException。