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
There is no way to get this count from SignalR as such. You have to use the
OnConnect()
andOnDisconnect()
methods on the Hub to keep the count yourself.Simple example with a static class to hold the count:
You then get the count from
UserHandler.ConnectedIds.Count
.For version 2.1.1+ it should be:
Now you need: