有没有办法找出听众的数量(连接到集线器的客户端?)
我试图运行/启动任务,如果至少一个客户端连接,否则不启动它:
[HubName("taskActionStatus")] public class TaskActionStatus : Hub,IDisconnect { static CancellationTokenSource tokenSource; public void GetTasksStatus(int? siteId) { tokenSource = new CancellationTokenSource(); CancellationToken ct = tokenSource.Token; ITaskRepository taskRepository = UnityContainerSetup.Container.Resolve<ITaskRepository>(); // init task for checking task statuses var tasksItem = new DownloadTaskItem(); taskRepository.GetTasksStatusAsync(siteId,tasksItem,ct); // subscribe to event [ listener ] tasksItem.Changed += new EventHandler<TaskEventArgs>(UpdateTasksStatus); } public void UpdateTasksStatus(object sender,TaskEventArgs e) { Clients.updateMessages(e.Tasks); } // when browsing away from page public Task Disconnect() { try { tokenSource.Cancel(); } catch (Exception) { // } return null; } }
谢谢
解决方法
没有办法从SignalR这样计数。您必须在集线器上使用OnConnect()和OnDisconnect()方法自己保存计数。
使用静态类来保存计数的简单示例:
public static class UserHandler { public static HashSet<string> ConnectedIds = new HashSet<string>(); } public class MyHub : Hub { public override Task OnConnected() { UserHandler.ConnectedIds.Add(Context.ConnectionId); return base.OnConnected(); } public override Task OnDisconnected() { UserHandler.ConnectedIds.Remove(Context.ConnectionId); return base.OnDisconnected(); } }
然后从UserHandler.ConnectedIds.Count获取计数。