Back to results for “Generic Host”
.NET › Generic Host

How would you implement a startup task that must complete successfully before the Generic Host considers the application ready to serve traffic or process work?

Advanced

Answer

One pattern uses a dedicated IHostedService (registered first) whose StartAsync performs the critical startup work (like verifying database connectivity or warming a cache) and doesn't return until it completes, blocking subsequent hosted services' StartAsync calls (since they run sequentially in registration order) from starting until this prerequisite finishes -- alternatively, for readiness-gate scenarios specifically, a health check reporting 'not ready' until initialization completes, combined with a Kubernetes readiness probe, ensures no traffic is routed to the pod prematurely even if the process has technically started.
public class DatabaseReadinessService : IHostedService {
    public async Task StartAsync(CancellationToken ct) {
        await _db.Database.CanConnectAsync(ct);  // blocks until DB is verified reachable
        _readinessState.MarkReady();
    }
    public Task StopAsync(CancellationToken ct) => Task.CompletedTask;
}
// Registered BEFORE other hosted services to enforce ordering
Real-world example A service depending on a message broker registers a startup connectivity-check hosted service first, ensuring the broker connection is verified and established before any message-processing background services begin, avoiding a race condition on startup.

Common follow-ups: How does this interact with a Kubernetes readiness probe for traffic gating?;What happens if this critical startup task itself times out or fails?