How do you register and run multiple independent BackgroundServices within the same application?
Short answer
Each BackgroundService is registered independently via `builder.Services.AddHostedService ()`, and the Generic Host starts all registered hosted services concurrently at application startup (each running its own independent ExecuteAsync loop) and stops them all (respecting the…
Advertisement
AModel answer
Each BackgroundService is registered independently via `builder.Services.AddHostedService<T>()`, and the Generic Host starts all registered hosted services concurrently at application startup (each running its own independent ExecuteAsync loop) and stops them all (respecting the shutdown timeout) when the application shuts down -- they don't interfere with each other unless they explicitly share state or resources.
builder.Services.AddHostedService<EmailQueueProcessor>();
builder.Services.AddHostedService<CacheWarmupService>();
builder.Services.AddHostedService<MetricsCollectorService>();
// All three run concurrently, independently, for the app's lifetimeReal-world example
A single worker service application runs three unrelated BackgroundServices simultaneously -- one polling a queue, one refreshing a cache every hour, and one exporting metrics every minute -- each isolated in its own loop within one deployed process.
Likely follow-ups
- Does the order of AddHostedService calls guarantee start order?
- How would you make one hosted service wait for another to finish starting?
Related topics