SignalR Core: Heartbeat and Redis

public async Task OnConnectedAsync()
{
...
_clientList.CreateUser(Context.ConnectionId);
...
}
public async Task OnDisconnectedAsync(Exception ex)
{
...
_clientList.RemoveUser(Context.ConnectionId);
...
}

Solutions

public async Task OnConnectedAsync()
{
try {
...
_clientList.CreateUser(Context.ConnectionId);
...
}
catch (Exception ex) {
// put your logger logic here
Context.Abort();
}
}

For advanced usage, this is not a proper solution. You have to make sure that Redis is always online, or have a backup plan in order to prevent server uptime loss.

private void Heartbeat()
{
var heartbeat = Context.Features.Get<IConnectionHeartbeatFeature>();
heartbeat.OnHeartbeat(state => {
(HttpContext context ,string connectionId) = ((HttpContext, string))state;
var ClientList = context.RequestServices.GetService<IClientList>();
ClientList.LatestPing(connectionId);
}, (Context.GetHttpContext(), Context.ConnectionId));
}
Result

Conclusion

UPDATE

Random rnd = new Random((int)DateTime.Now.Ticks);
public async Task OnConnectedAsync()
{
var heartbeat = Context.Features.Get<IConnectionHeartbeatFeature>();heartbeat.OnHeartbeat(state => {
if (rnd.Next(0, 100) >= 10)
return;
(HttpContext context ,string connectionId) = ((HttpContext, string))state;
var ClientList = context.RequestServices.GetService<IClientList>();
ClientList.LatestPing(connectionId);
}, (Context.GetHttpContext(), Context.ConnectionId));
}

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store