[英]ASP .Net Core Queued background tasks parallel processing
我有一个 ASP .NET 核心 Web API 使用此处描述的排队后台任务。
我使用了提供的代码示例,并完全按照文章中的描述添加了IBackgroundTaskQueue
、 BackgroundTaskQueue
和QueuedHostedService
。
在我的Startup.cs
中,我只注册了一个QueuedHostedService
实例,如下所示: services.AddHostedService<QueuedHostedService>();
来自 WebApi 的 controller 的任务被排队,然后由QueuedHostedService
执行。
我希望允许多个后台处理线程出列并执行传入的任务。 我能想到的最直接的解决方案是在我的Startup.cs
中注册多个QueuedHostedService
实例。 即,像这样:
int maxNumOfParallelOperations;
var isValid = int.TryParse(Configuration["App:MaxNumOfParallelOperations"], out maxNumOfParallelOperations);
maxNumOfParallelOperations = isValid && maxNumOfParallelOperations > 0 ? maxNumOfParallelOperations : 2;
for (int index = 0; index < maxNumOfParallelOperations; index++)
{
services.AddHostedService<QueuedHostedService>();
}
我还注意到,由于BackgroundTaskQueue
中的信号量, QueuedHostedService
实例并不是一直都在工作,而是只有在队列中有新任务可用时才会唤醒。
这个解决方案在我的测试中似乎工作得很好。
但是,在这个特定的用例中——它真的是一个有效的、推荐的并行处理解决方案吗?
您可以使用具有多个线程的IHostedService
来使用IBackgroundTaskQueue
。
这是一个基本的实现。 我假设您使用的是此处描述的相同IBackgroundTaskQueue
和BackgroundTaskQueue
。
public class QueuedHostedService : IHostedService
{
private readonly ILogger _logger;
private readonly Task[] _executors;
private readonly int _executorsCount = 2; //--default value: 2
private CancellationTokenSource _tokenSource;
public IBackgroundTaskQueue TaskQueue { get; }
public QueuedHostedService(IBackgroundTaskQueue taskQueue,
ILoggerFactory loggerFactory,
IConfiguration configuration)
{
TaskQueue = taskQueue;
_logger = loggerFactory.CreateLogger<QueuedHostedService>();
if (ushort.TryParse(configuration["App:MaxNumOfParallelOperations"], out var ct))
{
_executorsCount = ct;
}
_executors = new Task[_executorsCount];
}
public Task StartAsync(CancellationToken cancellationToken)
{
_logger.LogInformation("Queued Hosted Service is starting.");
_tokenSource = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
for (var i = 0; i < _executorsCount; i++)
{
var executorTask = new Task(
async () =>
{
while (!cancellationToken.IsCancellationRequested)
{
#if DEBUG
_logger.LogInformation("Waiting background task...");
#endif
var workItem = await TaskQueue.DequeueAsync(cancellationToken);
try
{
#if DEBUG
_logger.LogInformation("Got background task, executing...");
#endif
await workItem(cancellationToken);
}
catch (Exception ex)
{
_logger.LogError(ex,
"Error occurred executing {WorkItem}.", nameof(workItem)
);
}
}
}, _tokenSource.Token);
_executors[i] = executorTask;
executorTask.Start();
}
return Task.CompletedTask;
}
public Task StopAsync(CancellationToken cancellationToken)
{
_logger.LogInformation("Queued Hosted Service is stopping.");
_tokenSource.Cancel(); // send the cancellation signal
if (_executors != null)
{
// wait for _executors completion
Task.WaitAll(_executors, cancellationToken);
}
return Task.CompletedTask;
}
}
您需要在Startup
class 时在ConfigureServices
中注册服务。
...
services.AddSingleton<IBackgroundTaskQueue, BackgroundTaskQueue>();
services.AddHostedService<QueuedHostedService>();
...
此外,您可以在配置中设置线程数( appsettings.json
)
...
"App": {
"MaxNumOfParallelOperations": 4
}
...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.