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 t
I have done this way:
public class PrincipalCommunicator
{
public readonly static Lazy _instance = new Lazy(
() => new PrincipalCommunicator(GlobalHost.ConnectionManager.GetHubContext())
);
public List ConnectedUsers { get; set; }
private IHubContext _context;
private PrincipalCommunicator(IHubContext context)
{
ConnectedUsers = new List();
_context = context;
}
public static PrincipalCommunicatorInstance
{
get
{
return _instance.Value;
}
}
public bool IsUserConnected(string user)
{
return UsuariosConectados.Contains(user);
}
}
public class PrincipalHub : Hub
{
public override Task OnConnected()
{
PrincipalComunicador.Instance.UsuariosConectados.Add(Context.User.Identity.Name);
return base.OnConnected();
}
public override Task OnDisconnected(bool stopCalled)
{
PrincipalComunicador.Instance.UsuariosConectados.Remove(Context.User.Identity.Name);
return base.OnDisconnected(stopCalled);
}
}
}
This way, all logic to send something to client stays in one place, like the example and you can know if a user is connected anywhere in the code.