简体   繁体   中英

SignalR Core how to send message to clients every n seconds

AKA "Send messages to clients from a background service"

I would like my SignalR server to update a dashboard every n seconds. I'm using this right now:

public class MyHub : Hub
{
    public override Task OnConnectedAsync()
    {
        Observable.Interval(TimeSpan.FromSeconds(0.5)).Subscribe(l =>
        {
            var alt = CalcAltitude(l);
            SendMessage(alt);
        });

        return Task.CompletedTask;
    }

    private void SendMessage(double alt)
    {
        Clients.All.SendAsync("SendAction", new Status() {Altitude = alt});
    }

    private double CalcAltitude(long l)
    {
        return 100 * Math.Sin((double) l / 100) + 200;
    }
}

public class Status
{
    public double Altitude { get; set; }
}

When my code is executed, it throws an exception saying that

cannot access a disposed object

I suspect I'm doing something wrong here.

So, what's the correct way to make send messages to all the clients on a timely manner?

OK, this time the answer didn't come from Stack Overflow, but from another source.

This can be done with this code in ASP.NET Core + SignalR Core.

You'll need 2 parts.

Big thanks to David Fowler for the reply!

var hubContext = GlobalHost.ConnectionManager.GetHubContext<MyHub>();
hubContext.Clients.All.SendnewData(Data);

Put this code where your data is updated or calculated in every second.

Like: Your DB process is done then Broadcast new data

using Microsoft.AspNet.SignalR;
using Microsoft.AspNet.SignalR.Infrastructure;
using Microsoft.AspNet.Mvc;

public class TestController : Controller
{
     private IHubContext testHub;

     public TestController(IConnectionManager connectionManager)
     {
         testHub = connectionManager.GetHubContext<TestHub>();
         testHub.Clients.All.SendnewData(Data);
     }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM