我有一个在.net通用主机中托管的BackgroundService,如下所示:
var builder = Host.CreateDefaultBuilder(args);
builder
.ConfigureLogging((hostingContext, logging) =>
{
logging.ClearProviders();
logging.AddConsole();
if(hostingContext.HostingEnvironment.IsDevelopment() == true)
logging.AddDebug();
})
.ConfigureHostConfiguration(configurationBuilder =>
{
configurationBuilder.AddCommandLine(args);
})
.ConfigureAppConfiguration((hostingContext, configApp) =>
{
var env = hostingContext.HostingEnvironment;
Console.WriteLine(env.EnvironmentName);
})
.UseConsoleLifetime();
接下来我会定义我的工作线程:
public class Worker : BackgroundService
{
private readonly ILogger<Worker> _logger;
public Worker(ILogger<Worker> logger)
{
_logger = logger;
}
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
// here i am doing something with ClientWebSocket, threads etc
// snipped for brevity. I want to avoid spinning in a loop
// the debugger reaches the following line
WaitHandle.WaitAny(new[] { stoppingToken.WaitHandle });
// but never hits this line
this.logger.LogInformation("shutting down worker");
}
}
在运行应用程序的 Windows 终端中按下 ctrl+c 时,它会显示“Application is shutting down”(来自框架),但是 stoppingToken 从未被设置(因此我无法关闭我的工作进程)。
停止令牌是何时设置的?如何设置并优雅地终止工作进程?
控制台。
stopping token.IsCancellationRequested==true
,但我想在一些代码片段的异步函数调用上使用取消标记(将其作为参数传递给CancellationToken)。 - morleyc