Introduction
In the previous lessons, you learned how clients invoke Hub methods and how the server sends real-time notifications to connected clients. In production applications, however, not every event starts with an HTTP request or direct user interaction. Scheduled jobs, queue consumers, external data feeds, report generation, and maintenance tasks can all run in the application background.
In this lesson, we will send SignalR messages from a BackgroundService. We will build a periodic system monitor that sends status updates to every connected client, private notifications to a specific user, and job updates to a group. We will also cover graceful shutdown with CancellationToken, correct handling of scoped services, and testing failed background operations.
The central idea is to use IHubContext<THub> or the strongly typed IHubContext<THub, TClient> supplied by dependency injection. A Hub should not be instantiated manually. Hub context is the server-side entry point for reaching SignalR clients from controllers, application services, hosted services, and other components outside a Hub invocation.
1. IHostedService and BackgroundService
IHostedService is the basic contract used by the host to call StartAsync when the application starts and StopAsync during shutdown. It is useful for short startup and shutdown operations. For continuously running loops, BackgroundService is usually more convenient because it provides the ExecuteAsync method.
Hosted services are registered as singletons. Therefore, directly injecting a scoped service such as a database context into a hosted service is not the correct pattern. Create a dependency-injection scope for each unit of work and resolve scoped services inside that scope.
2. Define a strongly typed Hub
First, define the methods that the server may call on clients. A client interface avoids repeating string-based event names and allows the compiler to validate server-side calls.
public interface IMonitoringClient
{
Task SystemStatusChanged(SystemStatusDto status);
Task JobProgressChanged(JobProgressDto progress);
Task PrivateNotification(NotificationDto notification);
}
public sealed record SystemStatusDto(
DateTimeOffset RecordedAt,
double CpuUsage,
string State);
public sealed record JobProgressDto(
string JobId,
int Percent,
string State);
public sealed record NotificationDto(
string Title,
string Message,
DateTimeOffset CreatedAt);
public sealed class MonitoringHub : Hub<IMonitoringClient>
{
public Task JoinOperationsGroup()
{
return Groups.AddToGroupAsync(
Context.ConnectionId,
"operations");
}
}The Hub allows a client to invoke JoinOperationsGroup and join the operations group. The background service can then send messages through Clients.Group("operations").
3. Register the Hub and hosted service
Register SignalR and the background service in Program.cs. The mapped endpoint defines the URL used by clients to establish their Hub connection.
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddSignalR();
builder.Services.AddHostedService<SystemMonitorService>();
builder.Services.AddScoped<IReportService, ReportService>();
var app = builder.Build();
app.MapHub<MonitoringHub>("/hubs/monitoring");
app.Run();A service registered with AddHostedService is started by the host and stopped during application shutdown. Registering the Hub class alone is not enough; the SignalR services must also be added with AddSignalR.
4. Send messages to all clients with IHubContext
The following service generates a sample system status every five seconds and sends it to all connected clients. Because it uses IHubContext<MonitoringHub, IMonitoringClient>, client methods are called in a strongly typed way.
public sealed class SystemMonitorService : BackgroundService
{
private readonly IHubContext<MonitoringHub, IMonitoringClient> _hubContext;
private readonly ILogger<SystemMonitorService> _logger;
public SystemMonitorService(
IHubContext<MonitoringHub, IMonitoringClient> hubContext,
ILogger<SystemMonitorService> logger)
{
_hubContext = hubContext;
_logger = logger;
}
protected override async Task ExecuteAsync(
CancellationToken stoppingToken)
{
using var timer = new PeriodicTimer(TimeSpan.FromSeconds(5));
try
{
while (await timer.WaitForNextTickAsync(stoppingToken))
{
var status = new SystemStatusDto(
DateTimeOffset.UtcNow,
Random.Shared.NextDouble() * 100,
"Healthy");
await _hubContext.Clients.All
.SystemStatusChanged(status);
await _hubContext.Clients.Group("operations")
.JobProgressChanged(new JobProgressDto(
"system-monitor",
100,
"Completed"));
_logger.LogInformation(
"System status broadcast at {RecordedAt}",
status.RecordedAt);
}
}
catch (OperationCanceledException) when (stoppingToken.IsCancellationRequested)
{
_logger.LogInformation("System monitor is stopping.");
}
}
}PeriodicTimer is a readable way to manage recurring intervals. Passing the stopping token to WaitForNextTickAsync is essential. When the host requests shutdown, the wait is canceled and the service can finish in a controlled manner.
5. Send messages to users and groups
In SignalR, Clients.All targets every connection, Clients.Group targets a named group, and Clients.User targets all connections associated with one user. If a user is connected from both a desktop and a phone, a user message can reach both connections.
public async Task NotifyUserAsync(
string userId,
string title,
string message,
CancellationToken cancellationToken)
{
var notification = new NotificationDto(
title,
message,
DateTimeOffset.UtcNow);
await _hubContext.Clients.User(userId)
.PrivateNotification(notification);
await _hubContext.Clients.Group("operations")
.JobProgressChanged(new JobProgressDto(
"notification-job",
100,
"Completed"));
}The userId passed to this method must match the SignalR user identifier associated with the connection. By default, SignalR obtains that identifier from the ClaimTypes.NameIdentifier claim. When using JWT authentication, verify that the user identifier claim contains the value expected by the application.
6. Use scoped services correctly
Because a hosted service is a singleton, create a scope for each iteration when you need a scoped service. Imagine that the application has a service that stores system measurements in a database:
public interface IReportService
{
Task<SystemStatusDto> CreateStatusAsync(
CancellationToken cancellationToken);
}
public sealed class SystemMonitorService : BackgroundService
{
private readonly IServiceScopeFactory _scopeFactory;
private readonly IHubContext<MonitoringHub, IMonitoringClient> _hubContext;
private readonly ILogger<SystemMonitorService> _logger;
public SystemMonitorService(
IServiceScopeFactory scopeFactory,
IHubContext<MonitoringHub, IMonitoringClient> hubContext,
ILogger<SystemMonitorService> logger)
{
_scopeFactory = scopeFactory;
_hubContext = hubContext;
_logger = logger;
}
protected override async Task ExecuteAsync(
CancellationToken stoppingToken)
{
using var timer = new PeriodicTimer(TimeSpan.FromSeconds(10));
while (await timer.WaitForNextTickAsync(stoppingToken))
{
try
{
await using var scope = _scopeFactory.CreateAsyncScope();
var reportService = scope.ServiceProvider
.GetRequiredService<IReportService>();
var status = await reportService
.CreateStatusAsync(stoppingToken);
await _hubContext.Clients.All
.SystemStatusChanged(status);
}
catch (OperationCanceledException)
when (stoppingToken.IsCancellationRequested)
{
break;
}
catch (Exception exception)
{
_logger.LogError(
exception,
"Background status operation failed.");
}
}
}
}Rather than keeping one scope open for the entire lifetime of the service, create a scope for each unit of work. This allows scoped resources such as DbContext instances to be released at the appropriate time.
7. Listen for events in the JavaScript client
The client establishes a connection and listens for the methods defined by the client interface. Method names are case-sensitive in practice, so use names that match the server-side contract.
const connection = new signalR.HubConnectionBuilder()
.withUrl("/hubs/monitoring")
.withAutomaticReconnect()
.build();
connection.on("SystemStatusChanged", status => {
console.log("System state:", status.state);
console.log("CPU:", status.cpuUsage);
});
connection.on("JobProgressChanged", progress => {
console.log(`${progress.jobId}: ${progress.percent}%`);
});
connection.on("PrivateNotification", notification => {
console.log(notification.title, notification.message);
});
await connection.start();
await connection.invoke("JoinOperationsGroup");Even when automatic reconnect is enabled, decide how group membership should be restored after a new connection is established. Depending on the application, the client may need to request group membership again, or the Hub may add the connection during its connection lifecycle.
8. Failed operations and error handling
An unhandled exception in a background loop can stop the service or cause unexpected host behavior. Catch expected failures at the appropriate boundary, log the exception, and send a safe status event to operational clients when necessary.
try
{
await ProcessBatchAsync(stoppingToken);
}
catch (OperationCanceledException)
when (stoppingToken.IsCancellationRequested)
{
_logger.LogInformation("Batch processing cancelled.");
}
catch (Exception exception)
{
_logger.LogError(exception, "Batch processing failed.");
await _hubContext.Clients.Group("operations")
.JobProgressChanged(new JobProgressDto(
"batch-42",
0,
"Failed"));
}Do not send database connection strings, stack traces, or sensitive exception details to clients. Send a meaningful but safe status value and keep diagnostic details in server logs.
Common mistakes
- Creating a Hub with new: Hub instances are connection-scoped. Use
IHubContextinstead. - Injecting a scoped service directly: A hosted service is a singleton, so create a scope when resolving scoped dependencies.
- Ignoring cancellation during delays: The application may wait unnecessarily during shutdown. Use
Task.Delay(delay, stoppingToken)orPeriodicTimer. - Logging cancellation as a failure: An
OperationCanceledExceptioncaused by the stopping token normally represents controlled shutdown. - Broadcasting too frequently: Large payloads sent every second can overload clients and the network. Measure interval, payload size, and connection count.
- Using the wrong user identifier: The value passed to
Clients.Usermust match the identity claims used by SignalR. - Ignoring multi-server behavior: When multiple application instances are deployed, design how connections and messages are distributed between servers.
Short practice exercise
- Create the
MonitoringHubandIMonitoringClienttypes. - Write a
BackgroundServicethat generates a simulated queue length every ten seconds. - Send the status to all clients through
Clients.All. - Add a test condition that sends a failed-job message to clients in the
operationsgroup. - Create a scoped
IReportServiceand resolve it withCreateAsyncScopeon every iteration. - Stop the application and verify that the logs show a clean shutdown.
- Disconnect the client and test whether group notifications behave as expected after reconnection.
Conclusion
In this lesson, you learned that SignalR messages can originate not only from Hub methods but also from background operations. IHubContext provides access to all clients, individual users, and groups without requiring a Hub instance. BackgroundService offers a practical foundation for periodic work, CancellationToken enables graceful shutdown, and explicit scopes preserve the correct lifetime of scoped dependencies.
You can extend this pattern by combining it with queues, external messaging systems, and multi-server deployment. In production, also consider retry policies, idempotency, observability, rate limiting, and distributed SignalR options such as Redis or Azure SignalR Service.
Sources
- https://learn.microsoft.com/en-us/aspnet/core/signalr/background-services?view=aspnetcore-10.0
- https://learn.microsoft.com/en-us/aspnet/core/fundamentals/host/hosted-services?view=aspnetcore-10.0
- https://learn.microsoft.com/en-us/dotnet/core/extensions/scoped-service?pivots=dotnet-6-0
- https://learn.microsoft.com/en-us/aspnet/core/signalr/groups?view=aspnetcore-10.0
- https://learn.microsoft.com/en-us/aspnet/core/signalr/hubs?view=aspnetcore-10.0