signalR:调用OnDisconnected时的延迟

时间:2013-07-03 09:23:50

标签: signalr signalr-hub

当我用F5刷新浏览器页面时,OnDisconnected函数不会立即被调用。在调用函数之前有几秒钟的延迟,使得时间戳值为invalids。

 public override System.Threading.Tasks.Task OnDisconnected()

为什么会这样?这是signalR中的正常行为吗?

2 个答案:

答案 0 :(得分:0)

是的,这很正常。它发生在客户端断开连接时 - 当你执行刷新页面时,它首先调用OnDisconnected(),然后在OnConnected()之后再次加载页面。 它还有任务OnReconnected() - 但是当你在代码中重新连接程序时它会被调用。

答案 1 :(得分:0)

只是为了进一步扩展这一点。 SignalR 有一段时间会在连接终止后等待,然后再调用 OnDisconnected。默认为 10 秒,但您可以在 Global.asax 文件中覆盖此设置(下面的示例)。遗憾的是,该值至少需要 6 秒,但我明白其背后的原因。

https://docs.microsoft.com/en-us/aspnet/signalr/overview/guide-to-the-api/handling-connection-lifetime-events#disconnecttimeout

protected void Application_Start(object sender, EventArgs e)
{
    // Make long polling connections wait a maximum of 110 seconds for a
    // response. When that time expires, trigger a timeout command and
    // make the client reconnect.
    GlobalHost.Configuration.ConnectionTimeout = TimeSpan.FromSeconds(110);
    
    // Wait a maximum of 30 seconds after a transport connection is lost
    // before raising the Disconnected event to terminate the SignalR connection.
    **GlobalHost.Configuration.DisconnectTimeout = TimeSpan.FromSeconds(6);**
    
    // For transports other than long polling, send a keepalive packet every
    // 10 seconds. 
    // This value must be no more than 1/3 of the DisconnectTimeout value.
    GlobalHost.Configuration.KeepAlive = TimeSpan.FromSeconds(10);
    
    RouteTable.Routes.MapHubs();
}

我处理这个问题的方式是在 OnConnected 函数中,我为客户端存储并寻找另一个唯一标识(在我的例子中是 IP 地址),如果我找到了那个客户端,继续并删除来自我的自定义会话集合的旧连接。