.net 核心工作者服务中的多个工作者? [英] Multiple Workers in .net core worker services?
问题描述
dot net core 3.0 worker服务模板如下图:
The dot net core 3.0 worker services template shown as follow:
public class Program
{
public static void Main(string[] args)
{
CreateHostBuilder(args).Build().Run();
}
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureServices(services =>
{
services.AddHostedService<Worker>();
});
}
Worker"类是从 BackgroundService 派生的.它每 1000 毫秒循环一次将日志写入控制台.
The "Worker" class is derived from BackgroundService. It loops to write log to console every 1000 ms.
我的问题:
我可以同时运行多个Worker"吗?(我知道我可以创建另一个类Worker2".但是我可以运行同一个类Worker"的两个副本吗?)
Can I run multiple "Worker"s simultaneously? (I know I can create another class "Worker2". But can I run two copies of same class "Worker"?)
如果是,我如何配置两个具有不同配置或参数的Worker",例如,两个具有不同循环间隔的 Worker?(因为Worker"类的实例是由DI框架创建的.我不知道如何将不同的配置/参数传递给Worker"的两个不同实例)
If yes, how I can configure two "Worker" with different configuration or parameters, say, two Workers with different looping intervals? (Because instance of "Worker" class is created by DI framework. I don't know how I can pass different config/parameters to two different instance of "Worker")
推荐答案
你可以让一个父"worker 像这样启动真正的"worker...
You can have a "parent" worker that launches the "real" workers like this...
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
while (!stoppingToken.IsCancellationRequested)
{
var workers = new List<Task>();
foreach(var delay in _config.LoopIntervals)
workers.Add(DoRealWork(delay, stoppingToken));
await Task.WhenAll(workers.ToArray());
}
}
那么……
private async Task DoRealWork(int delay, CancellationToken stoppingToken)
{
while (!stoppingToken.IsCancellationRequested)
{
_logger.LogInformation("worker {delay} checking in at {time}", delay, DateTimeOffset.Now);
await Task.Delay(delay, stoppingToken);
}
}
_config 从 appSettings.json 填充并像这样传递给 Worker 的构造函数...
_config gets populated from appSettings.json and passed in to the constructor of the Worker like this...
var cfg = hostContext.Configuration.GetSection(nameof(WorkerConfig)).Get<WorkerConfig>();
services.AddSingleton(cfg);
services.AddHostedService<Worker>();
和应用设置...
{
"WorkerConfig": {
"LoopIntervals": [ 1000, 2000, 3000 ]
}
}
这篇关于.net 核心工作者服务中的多个工作者?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!