问题描述
我有方法的集线器被称为客户端。这种方法启动一个定时器与每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)
{
return base.OnDisconnected(stopCalled);
}
// In your delegate check the count of users in your list.
}
这篇关于SignalR - 检查用户是否仍然连接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!