作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我在 .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");
}
}
Application is shutting down
(这是来自框架)但是停止 token 永远不会被设置(所以我不能关闭我的 worker )。
最佳答案
对于 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/
我在 .net 通用主机中托管了一个 BackgroundService,如下所示: var builder = Host.CreateDefaultBuilder(args); builder
我是一名优秀的程序员,十分优秀!