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

// 1 - Call Run on the builder (async)

RunConsoleAsync enables console support, builds and starts the host, and waits for Ctrl+C/SIGINT or SIGTERM to shut down. So as it's expected from its name it's for hosting your app in console only (not IIS, etc)

// 2 - Call Start on the builder (sync)

just starts the host synchronously

public static IHost Start(this IHostBuilder hostBuilder)
{
    var host = hostBuilder.Build();
    host.StartAsync(CancellationToken.None).GetAwaiter().GetResult();
    return host;
}

// 3 - Call Run on the host (sync / async)

RunAsync runs the app and returns a Task that completes when the cancellation token or shutdown is triggered. Sync is just a wrapper:

public static void Run(this IHost host)
{
    host.RunAsync().GetAwaiter().GetResult();
}

// 4 - Call Start on the host (sync / async)

This method is actually starting the program and it's called eventually from any other ways.


Updated for .NET Core 3.1.

Summary

  • Start methods start the service, and returns
  • Run methods start the service, then wait for it to stop before returning
  • Synchronous versions are all just wrappers to the actual async implmentations (.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);