ASP .Net Core 队列后台任务并行处理
ASP .Net Core Queued background tasks parallel processing
我有一个 ASP .NET 核心 Web API,它使用描述的排队后台任务
here.
我使用了提供的代码示例并完全按照文章中的描述添加了 IBackgroundTaskQueue
、BackgroundTaskQueue
和 QueuedHostedService
。
在我的 Startup.cs
中,我只注册了一个 QueuedHostedService
实例,如下所示:services.AddHostedService<QueuedHostedService>();
来自 WebApi 控制器的任务由 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
描述为 here.
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;
}
}
您需要在 ConfigureServices
Startup
class 注册服务。
...
services.AddSingleton<IBackgroundTaskQueue, BackgroundTaskQueue>();
services.AddHostedService<QueuedHostedService>();
...
此外,您可以在配置中设置线程数(appsettings.json
)
...
"App": {
"MaxNumOfParallelOperations": 4
}
...
我有一个 ASP .NET 核心 Web API,它使用描述的排队后台任务 here.
我使用了提供的代码示例并完全按照文章中的描述添加了 IBackgroundTaskQueue
、BackgroundTaskQueue
和 QueuedHostedService
。
在我的 Startup.cs
中,我只注册了一个 QueuedHostedService
实例,如下所示:services.AddHostedService<QueuedHostedService>();
来自 WebApi 控制器的任务由 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
描述为 here.
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;
}
}
您需要在 ConfigureServices
Startup
class 注册服务。
...
services.AddSingleton<IBackgroundTaskQueue, BackgroundTaskQueue>();
services.AddHostedService<QueuedHostedService>();
...
此外,您可以在配置中设置线程数(appsettings.json
)
...
"App": {
"MaxNumOfParallelOperations": 4
}
...