How do I call a SignalR hub method from the outside?

后端 未结 3 836
有刺的猬
有刺的猬 2020-12-30 03:53

This is my Hub code:

public class Pusher : Hub, IPusher
{
    readonly IHubContext _hubContext = GlobalHo         


        
3条回答
  •  醉梦人生
    2020-12-30 04:29

    Take a look at this link at the topic of (How to call client methods and manage groups from outside the Hub class).
    Code example simply creates a singleton instance of the caller class and pass in the IHubContext into it's constructor. Then you have access to desired context.Clients in caller class's methods:

    // This sample only shows code related to getting and using the SignalR context.
    public class StockTicker
    {
        // Singleton instance
        private readonly static Lazy _instance = new     Lazy(() => new StockTicker(GlobalHost.ConnectionManager.GetHubContext()));
    
    private IHubContext _context;
    
    private StockTicker(IHubContext context)
    {
        _context = context;
    }
    
    // This method is invoked by a Timer object.
    private void UpdateStockPrices(object state)
    {
        foreach (var stock in _stocks.Values)
        {
            if (TryUpdateStockPrice(stock))
            {
                _context.Clients.All.updateStockPrice(stock);
            }
        }
    }
    

提交回复
热议问题