SignalR - 检查用户是否仍处于连接状态 [英] SignalR - Checking if a user is still connected
问题描述
我有一个带有称为客户端的方法的集线器.此方法使用每 10 秒运行一次的委托启动一个计时器.由于在没有人连接到集线器的情况下继续运行此委托是没有意义的,因此我想在重新安排它之前检查是否仍有用户从委托内部连接.有没有办法做到这一点?
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?
推荐答案
可能最常用的解决方案是保留一个静态变量,其中包含当前连接的用户并覆盖 OnConnect
和 OnDisconnect
或根据您使用的版本实施 IDisconnect
.
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.
你会实现这样的事情:
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.
}
这篇关于SignalR - 检查用户是否仍处于连接状态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!