What’s the difference between these ways to start/run a Generic Host in ASP.NET Core?

Updated for .NET 6.

Summary

  • All these methods, except for RunConsoleAsync, operate on an IHost instance. The ones on IHostBuilder simply call IHost.Build() and then delegate to the IHost methods (e.g. IHostBuilder.StartAsync() is equivalent to IHostBuilder.Build().StartAsync()).
  • Start methods start the host and immediately return.
  • Run methods start the host and wait for it to complete before returning.
  • Synchronous versions are all just wrappers around the actual async implementations (.GetAwaiter().GetResult()).

Methods

StartAsync

Task IHost.StartAsync(CancellationToken cancellationToken = default)

Starts the host (web application). Task completes once the host is started.

Start

void Start(this IHost host)

Synchronous wrapper to IHost.StartAync.

RunAsync

Task RunAsync(this IHost host, CancellationToken token = default)
{
    using (host)
    {
        await host.StartAsync(token);
        await host.WaitForShutdownAsync(token);
    }
}

Starts the host. Task completes when the host shuts down, which can be trigger by cancelling the token or calling StopAsync() on another thread.

WaitForShutdownAsync

Task WaitForShutdownAsync(this IHost host, CancellationToken token = default)

Returns a task that completes when the application shuts down. Shutdown is initiated via the passed token, and cancelling the token causes the application to stop.

WaitForShutdown

void WaitForShutdown(this IHost host)

Synchronous wrapper to IHost.WaitForShutdownAync.

StopAsync

Task IHost.StopAsync(CancellationToken cancellationToken = default)

Gracefully stops the host, returning a task that completes once the host has stopped. Cancelling cancellationToken indicates stop should no longer be graceful.

There’s also an extension method that allows passing a Timeout instead:

public static Task StopAsync(this IHost host, TimeSpan timeout)
    => host.StopAsync(new CancellationTokenSource(timeout).Token);

RunConsoleAsync

Task RunConsoleAsync(this IHostBuilder hostBuilder, CancellationToken cancellationToken = default)
    => hostBuilder.UseConsoleLifetime().Build().RunAsync(cancellationToken);

source

This is the only one that uses IHostBuilder (instead of IHost) because it invokes UseConsoleLifetime() (which needs IHostBuilder). This also causes a wait for Ctrl+C to exit.

There’s also no corresponding Start method, which I can only speculate is because the vast majority of time in a console app this is all you’d need. The very few that run other backend services plus ASP.NET would probably be better off using RunAsync() and managing lifetime (ie: controlling the CancellationToken) themselves.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)