在.Net核心控制台应用程序中触发后台服务ExecuteAsync方法 [英] Trigger background service ExecuteAsync method in .Net core console application
本文介绍了在.Net核心控制台应用程序中触发后台服务ExecuteAsync方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在 asp.net core 中创建控制台应用程序,它将在不同环境中作为后台服务运行.我使用了Microsoft.Extensions.Hosting"提供的BackgroundService"类.我想在我的程序启动时运行它的ExecuteAsync"方法.
I am creating console application in asp.net core which is going to run as background service in different environments. I have used "BackgroundService" class provided by "Microsoft.Extensions.Hosting". I want to run its "ExecuteAsync" method when my program gets started.
文件:Program.cs
File: Program.cs
public static void Main(string[] args)
{
var host = new HostBuilder()
.ConfigureHostConfiguration(configHost =>
{
})
.ConfigureServices((hostContext, services) =>
{
services.AddHostedService<IHostedService,RabbitLister>();
})
.UseConsoleLifetime()
.Build();
}
文件:RabbitLister.cs
File: RabbitLister.cs
public class RabbitLister : BackgroundService
{
private readonly IEventBus _eventBus;
private readonly ILogger<RabbitLister> _logger;
public RabbitLister()
{
}
public RabbitLister(IEventBus eventBus, ILogger<RabbitLister> logger)
{
_eventBus = eventBus;
_logger = logger;
}
protected override Task ExecuteAsync(CancellationToken stoppingToken)
{
_eventBus.SubscribeDynamic("myQueue");
return Task.CompletedTask;
}
}
推荐答案
宿主构建完成后,调用 host.Run()
After the host has been build, invoke host.Run()
public static void Main(string[] args) {
var host = new HostBuilder()
.ConfigureHostConfiguration(configHost => {
})
.ConfigureServices((hostContext, services) => {
services.AddHostedService<IHostedService, RabbitLister>();
})
.UseConsoleLifetime()
.Build();
//run the host
host.Run();
}
这将启动托管服务并最终调用执行函数
that will start hosted service and eventually call the execute function
这篇关于在.Net核心控制台应用程序中触发后台服务ExecuteAsync方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文