.net核心工作人员服务中有多个工作人员? [英] Multiple Workers in .net core worker services?
问题描述
点网核心3.0工人服务模板显示如下:
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类的实例是由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")
推荐答案
您可以有一个父母工人,像这样启动真正工人...
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>();
和appSettings ...
and the appSettings...
{
"WorkerConfig": {
"LoopIntervals": [ 1000, 2000, 3000 ]
}
}
这篇关于.net核心工作人员服务中有多个工作人员?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!