Search code examples
c#.netsignalrsignalr-hub

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?


Solution

  • 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!