首页 > 解决方案 > 这些在 ASP.NET Core 中启动/运行通用主机的方法有什么区别?

问题描述

ASP.NET Core 中的托管设计现在有一个新的通用主机(.NET Core 2.1+),它将在未来取代 Web 主机。

有很多方法可以使用Microsoft.Extensions.Hosting接口IHostIHostBuilder.

我知道使用asyncvs之间的区别sync,但是所有这些选项之间有什么区别?使用RunvsStart和调用IHostBuildervs 调用IHost

请参阅下面的代码中的选项// 1// 2和:// 3// 4

using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace MyNamespace
{
    class Program
    {
        static async Task Main(string[] args)
        {
            IHostBuilder builder = CreateBuilder();

            // 1 - Call Run on the builder (async)
            await builder.RunConsoleAsync();    // extension method

            // 2 - Call Start on the builder (sync)
            builder.Start();                    // extension method

            IHost host = builder.Build();       // Call Build on the builder to get a host

            // 3 - Call Run on the host (sync / async)
            host.Run();                         // extension method
            await host.RunAsync();              // extension method

            // 4 - Call Start on the host (sync / async)
            host.Start();                       // extension method
            await host.StartAsync();            // class method
        }

        private static IHostBuilder CreateBuilder() => new HostBuilder()
            .ConfigureAppConfiguration((hostingContext, config) =>
            {
                //...
            })
            .ConfigureLogging((hostingContext, logging) => {
                //...
            })
            .ConfigureServices((hostContext, services) =>
            {
                //...
                services.AddSingleton<IHostedService, MyService>();
            });
    }
}

标签: c#asp.net-core.net-core

解决方案


针对 .NET Core 3.1 进行了更新。

概括

  • 启动方法启动服务,并返回
  • 运行方法启动服务,然后等待它停止再返回
  • 同步版本都只是实际异步实现的包装(.GetAwaiter().GetResult();

方法

开始异步

Task IHost.StartAsync(CancellationToken cancellationToken = default);

启动主机(Web 应用程序)。主机启动后任务完成。

开始

void Start(this IHost host);

同步包装器IHost.StartAync();

运行异步

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

启动主机。任务在主机关闭时完成,可以通过取消令牌或调用StopAsync()另一个线程来触发。

WaitForShutdownAsync

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

返回应用程序关闭时完成的任务。通过传递的令牌启动关闭,取消令牌会导致应用程序停止。

等待关机

void WaitForShutdown(this IHost host)

同步包装器IHost.WaitForShutdownAync();

停止异步

Task IHost.StopAsync(CancellationToken cancellationToken = default)

优雅地停止主机,返回一个在主机停止后完成的任务。取消cancellationToken表示停止应该不再是优雅的。

还有一个扩展方法允许传递 a Timeout

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

推荐阅读