如何以编程方式停止 HostedService?
How to stop HostedService programmatically?
我正在构建一个 dotnet 核心 HostedService 应用程序。我需要在一段时间后停止应用程序。
我该如何阻止它?
我尝试添加到 StartAsync 方法
await Task.Delay(5000);
Environment.Exit(0);
主要:
static Task Main(string[] args)
{
var hostBuilder = new HostBuilder()
.ConfigureServices((hostContext, services) =>
{
services.AddHostedService<EventsService>();
})
.UseLogging();
return hostBuilder.RunConsoleAsync();
}
没用。我怎样才能正确阻止它?
RunConsoleAsync
接受 CancellationToken
。您可以创建一个 CancellationTokenSource
在给定的毫秒数后发出取消信号:
var cancellationTokenSource = new CancellationTokenSource(5000);
return hostBuilder.RunConsoleAsync(cancellationTokenSource.Token);
有了这个,应用程序会在 大约 五秒后关闭。
我正在构建一个 dotnet 核心 HostedService 应用程序。我需要在一段时间后停止应用程序。
我该如何阻止它?
我尝试添加到 StartAsync 方法
await Task.Delay(5000);
Environment.Exit(0);
主要:
static Task Main(string[] args)
{
var hostBuilder = new HostBuilder()
.ConfigureServices((hostContext, services) =>
{
services.AddHostedService<EventsService>();
})
.UseLogging();
return hostBuilder.RunConsoleAsync();
}
没用。我怎样才能正确阻止它?
RunConsoleAsync
接受 CancellationToken
。您可以创建一个 CancellationTokenSource
在给定的毫秒数后发出取消信号:
var cancellationTokenSource = new CancellationTokenSource(5000);
return hostBuilder.RunConsoleAsync(cancellationTokenSource.Token);
有了这个,应用程序会在 大约 五秒后关闭。