Is there a way to find out the number of listeners (clients connected to a hub?)
I'm trying to run/start a task if at least one client is connected, otherwise do not start it:
[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; } }
thanks
A SignalR app can scale out based on the number of messages sent, while the Azure SignalR Service scales to handle any number of connections.
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.
There is no way to get this count from SignalR as such. You have to use the OnConnect()
and OnDisconnect()
methods on the Hub to keep the count yourself.
Simple example with a static class to hold the count:
public static class UserHandler { public static HashSet<string> ConnectedIds = new HashSet<string>(); } public class MyHub : Hub { public override Task OnConnectedAsync() { UserHandler.ConnectedIds.Add(Context.ConnectionId); return base.OnConnectedAsync(); } public override Task OnDisconnectedAsync(Exception exception) { UserHandler.ConnectedIds.Remove(Context.ConnectionId); return base.OnDisconnectedAsync(exception); } }
You then get the count from UserHandler.ConnectedIds.Count
.
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