A .NET console import tool built on Host.CreateApplicationBuilder finishes its work in a hosted service but never exits; why, and how should it be structured?
answer
- Run waits for a shutdown signal
- ConsoleLifetime listens for Ctrl+C and SIGTERM
- a finished hosted service stops nothing
- build, resolve, await, return
- SuppressStatusMessages
basics
~20 shost.Run() blocks until shutdown is triggered, which the default ConsoleLifetime does only on Ctrl+C, SIGQUIT or SIGTERM; a finished hosted service stops nothing. A one-shot tool builds the host, resolves its service, awaits it and returns an exit code.
solid answer
~40 s`host.Run()` starts every hosted service and then blocks until shutdown is triggered and the services have stopped. Shutdown starts when the default `IHostLifetime`, `ConsoleLifetime`, sees Ctrl+C, SIGINT, SIGQUIT or SIGTERM, or when code calls `IHostApplicationLifetime.StopApplication()`. A `BackgroundService` whose `ExecuteAsync` completes is just finished; the host keeps waiting. A one-shot tool should not use `Run()` at all: call `Build()` to get configuration, logging and DI, resolve the importer from `host.Services`, await it and return its result from `Main` as the exit code, disposing the host with `using`. If the work must stay a hosted service, it has to stop the application itself when done. Set `ConsoleLifetimeOptions.SuppressStatusMessages` to drop the "Application started. Press Ctrl+C to shut down." lines from the tool's output.
code
csharp · 15 linesHostApplicationBuilder builder = Host.CreateApplicationBuilder(args);
builder.Services.AddSingleton<Importer>();
using IHost host = builder.Build(); // configuration, logging and DI, but never Run()
Importer importer = host.Services.GetRequiredService<Importer>();
return await importer.RunAsync(); // the process ends here with this exit code
sealed class Importer(ILogger<Importer> logger, IConfiguration config)
{
public Task<int> RunAsync()
{
logger.LogInformation("Importing from {Source}", config["Import:Source"]);
return Task.FromResult(0);
}
}go deeper
Remember that Run() keeps a host alive until Ctrl+C or SIGTERM, and that a one-shot tool should return from Main instead.
Walk through what Run() does: ConsoleLifetime registers signal handlers, hosted services start, and nothing watches for a finished BackgroundService.
Structure tools so exit codes reach schedulers, output stays clean with SuppressStatusMessages, and the host is disposed even when the import throws.
Give the team one pattern for tools versus workers so scheduled jobs never hang and every job reports success through its exit code.
## Why `Run()` waits `host.Run()` is documented as running the application and blocking the calling thread **until host shutdown is triggered** and all `IHostedService` instances are stopped. With the default builder on desktop and server platforms, the piece that decides when shutdown is triggered is the registered **`IHostLifetime`**, which is `ConsoleLifetime`: 1. `StartAsync` first calls `ConsoleLifetime.WaitForStartAsync`, which returns at once ("console applications start immediately") after registering handlers for **SIGINT, SIGQUIT and SIGTERM**; Ctrl+C arrives as SIGINT. 2. The host calls `StartAsync` on every hosted service, sequentially unless `HostOptions.ServicesStartConcurrently` is `true`. 3. The host raises `ApplicationStarted`; `ConsoleLifetime` logs "Application started. Press Ctrl+C to shut down.", the hosting environment and the content root under the `Microsoft.Hosting.Lifetime` category. 4. `Run()` then waits for `ApplicationStopping`. Only a signal handler or a call to `StopApplication()` raises it. Nothing in that sequence watches whether a `BackgroundService` has finished. An `ExecuteAsync` that imports a file and returns leaves the host idle but alive, which is exactly what a long-running worker wants and exactly wrong for a tool. Running such a tool shows the import log line, the three lifetime lines, and then nothing until the process is signalled. ## Three ways to structure a one-shot tool | Approach | What runs | How the process ends | |---|---|---| | `Build()`, resolve the service, await it, never `Run()` | configuration, logging, DI; no hosted services start | `Main` returns the exit code | | Hosted service calls `StopApplication()` when done | full start and stop sequence | `Run()` returns after shutdown | | `await host.StartAsync()`, do the work, `await host.StopAsync()` | hosted services start and stop around your code | `Main` returns | The first is the usual answer. `Host.CreateApplicationBuilder(args)` still loads `appsettings.json`, `appsettings.{Environment}.json`, environment variables and the command line, registers the logging providers and builds the container, so the tool shares every configuration rule with the worker it ships beside. `using IHost host = builder.Build();` disposes the container, and the tool returns `0` or a failure code from `Main`, which is what schedulers and CI scripts check. The second keeps hosted-service structure, for example when the tool reuses a worker's services. The mechanics of `IHostApplicationLifetime` and the shutdown sequence are covered with application lifetime in the ASP.NET Core material; the point here is only that something must call it. ## Keeping the tool's output clean A command-line tool usually should not print hosting chatter: - `builder.Services.Configure<ConsoleLifetimeOptions>(o => o.SuppressStatusMessages = true)` stops `ConsoleLifetime` from registering its started and stopping messages. - Alternatively, raise the `Microsoft.Hosting.Lifetime` category's level in the `Logging:LogLevel` section; the worker template sets that category explicitly in `appsettings.json` for this reason. ## Exit codes and disposal - Return the code from `Main` (`return await importer.RunAsync();` in top-level statements); avoid `Environment.Exit` inside services, which ends the process without the host's stop sequence or the `using` that disposes it. - `host.RunAsync()` disposes the host after running; with `Build()` and no `Run()`, dispose it yourself with `using` or `await using`. - Exceptions thrown by your service propagate out of `Main` and give a non-zero exit code, which is usually what an operator wants from a failed import. ## Recognising a hung tool The symptoms are distinctive once you know them: - The log shows the tool's own completion message followed by "Application started. Press Ctrl+C to shut down." and nothing after it; that line means the host is inside `Run()` and waiting. - A scheduler or CI job reports a timeout rather than a failure, because the process never returned an exit code. - Sending SIGTERM (or pressing Ctrl+C locally) prints "Application is shutting down..." and the process then exits, which proves the work finished long before. The fix is structural, not a timeout: move the work out of `Run()` as described above, or make the hosted service end the application when it is done. ## When `Run()` is right `Run()` is the right call for the **worker**: a process that consumes a queue until the service manager, container runtime or operator stops it. The same project can contain both shapes, for example a `Program.cs` that runs the worker by default and runs a one-shot import when a command-line verb is present, each built from one `Host.CreateApplicationBuilder(args)` call.
- Which signals make the default ConsoleLifetime start a graceful shutdown on Linux?SIGINT, SIGQUIT and SIGTERM. Its handler cancels the default termination and calls `StopApplication()`, so the host runs its stop sequence and `Run()` returns. A SIGKILL cannot be handled, so nothing in the host runs.
- What changes if the tool sets `HostOptions.ServicesStartConcurrently` to `true`?The host calls `StartAsync` on all hosted services concurrently instead of one after another, so start-up takes as long as the slowest service rather than the sum. The default is `false`; it can also be set with the `servicesStartConcurrently` configuration key.
- host.Run() returns as soon as the last BackgroundService finishes its work.
- The host restarts ExecuteAsync when it completes, so a one-shot loop repeats.
- Resolving services from host.Services requires host.StartAsync() first.
- The status lines can only be removed by deleting the console logger.
- Environment.Exit inside a hosted service is the clean way to end a tool.