c# - 这些在 ASP.NET Core 中启动/运行通用主机的方法有什么区别?
问题描述
ASP.NET Core 中的托管设计现在有一个新的通用主机(.NET Core 2.1+),它将在未来取代 Web 主机。
有很多方法可以使用Microsoft.Extensions.Hosting
接口IHost
和IHostBuilder
.
我知道使用async
vs之间的区别sync
,但是所有这些选项之间有什么区别?使用Run
vsStart
和调用IHostBuilder
vs 调用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>();
});
}
}
解决方案
针对 .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);
推荐阅读
- javascript - Javascript 同步运行多个作业(vuejs、axios)
- javascript - React Native Geolocation:为什么这个异步函数返回未定义?
- excel - 去除命名范围左侧的空列
- javascript - 使用 React Hooks - 状态不更新
- php - php会话和htaccess保护图像文件夹不起作用
- java - 如何在Java中使用正则表达式模式在字符串的最后一个字母之前插入一个-符号
- java - IDEA 更新 Maven 索引无法更新
- node.js - 流星英雄/ Heroku。部署失败。Meteor 需要 Node v12.0.0 或更高版本。code=H10 desc="应用程序崩溃"
- python - python如何从静态类型语言实现类型自由变量
- swift - 获取 tableview 单元格按钮以添加新的 tableview 单元格