gpt4 book ai didi

c# - BackgroundService 未关闭,stoppedToken 从未使用 .net 核心通用主机设置

转载 作者:行者123 更新时间:2023-12-04 10:14:59 30 4
gpt4 key购买 nike

我在 .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();

然后我有我的 worker :
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 (这是来自框架)但是停止 token 永远不会被设置(所以我不能关闭我的 worker )。

如何以及何时设置停止 token ,以及如何优雅地终止我的工作人员?

控制台

最佳答案

对于 BackgroundServices,它们需要继续运行,直到取消 token 说停止。为此,您需要一个 while 循环。但是,当您将此取消 token 传递给任何 Async 方法时,如果您在所有层中使用相同的 token ,它将停止该方法在整个链中运行。它应该是这样的:

  protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
while (!stoppingToken.IsCancellationRequested)
{
// here i am doing something with ClientWebSocket, threads etc
// snipped for brevity. I want to avoid spinning in a loop
...
await client.DownloadAsync(..., stoppingToken);
...
}

// but never hits this line
this.logger.LogInformation("shutting down worker");
}

关于c# - BackgroundService 未关闭,stoppedToken 从未使用 .net 核心通用主机设置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61109752/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com