.net 通用主机状态的 .net文档
主机是封装应用程序资源和生命周期功能的对象
然而,它并没有说支持在单个进程中运行多个主机(即应用程序)。下面的代码运行得很好,并很好地终止了所有正在运行Host
的 s 和服务Ctrl-C
。但这只是一个非常简单的演示......
问题是:通用主机(或控制台主机或后台工作人员)是否存在排除“单个进程中的多个主机”选项的限制?
private static async Task Main()
{
await RunMultipleHosts();
async Task RunMultipleHosts()
{
var hostTasks = new[]
{
RunHostFor("service in host 1"),
RunHostFor("service in host 2"),
RunHostFor("service in host 3")
};
await Task.WhenAll(hostTasks);
}
static Task RunHostFor(string serviceName)
{
return Host
.CreateDefaultBuilder()
.ConfigureServices(services =>
{
services
.AddSingleton(new TestService.Name(serviceName))
.AddHostedService<TestService>();
})
.RunConsoleAsync();
}
}
使用以下简单的演示服务(为了完整起见,复制到这里)
internal class TestService : IHostedService
{
private readonly ILogger<TestService> logger;
private readonly string name;
private readonly Random random = new();
public TestService(Name serviceName, ILogger<TestService> logger)
{
this.logger = logger;
name = serviceName.Value;
}
Task IHostedService.StartAsync(CancellationToken cancellationToken)
{
logger.LogWarning($"Started {name}.");
return Task.CompletedTask;
}
async Task IHostedService.StopAsync(CancellationToken cancellationToken)
{
var aFewSeconds = random.Next(2000, 5000);
await Task.Delay(aFewSeconds, cancellationToken);
logger.LogWarning($"Stopped {name}.");
}
internal record Name(string Value);
}