I have a hub with method that is called client-side. This method launches a timer with a delegate that runs every 10 seconds. Since it wouldn't make sense to keep running this delegate if no one is connected to the hub, I want to check if any users are still connected from inside the delegate before I reschedule it. Is there any way to do this?
The default keepalive timeout period is currently 20 seconds. If your client code tries to call a Hub method while SignalR is in reconnecting mode, SignalR will try to send the command. Most of the time, such attempts will fail, but in some circumstances they might succeed.
Probably the most used solution is to keep a static variable containing users currently connected and overriding OnConnect
and OnDisconnect
or implementing IDisconnect
depending on the version that you use.
You would implement something like this:
public class MyHub : Hub
{
private static List<string> users = new List<string>();
public override Task OnConnected()
{
users.Add(Context.ConnectionId);
return base.OnConnected();
}
//SignalR Verions 1 Signature
public override Task OnDisconnected()
{
users.Remove(Context.ConnectionId);
return base.OnDisconnected();
}
//SignalR Version 2 Signature
public override Task OnDisconnected(bool stopCalled)
{
users.Remove(Context.ConnectionId);
return base.OnDisconnected(stopCalled);
}
// In your delegate check the count of users in your list.
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With