4

我有一个 ASP .NET 核心 Web API,它使用 此处描述的排队后台任务。

我使用了提供的代码示例并添加了IBackgroundTaskQueue,BackgroundTaskQueueQueuedHostedService文章中描述的完全一样。

在我的Startup.cs中,我只注册了一个QueuedHostedService实例,如下所示:services.AddHostedService<QueuedHostedService>();

来自 WebApi 控制器的任务被排入队列,然后由QueuedHostedService.

我希望允许多个后台处理线程出列并执行传入的任务。我能想到的最直接的解决方案是QueuedHostedService在我的Startup.cs. 即,像这样:

 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>();
 }

我还注意到,由于 singal Semaphore in BackgroundTaskQueueQueuedHostedService实例并不是一直都在工作,而是只有在队列中有新任务可用时才会唤醒。

这个解决方案在我的测试中似乎工作得很好。

但是,在这个特定的用例中——它真的是一个有效的、推荐的并行处理解决方案吗?

4

1 回答 1

4

您可以使用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;
    }
}

您需要ConfigureServicesStartup课堂上注册服务。

...
services.AddSingleton<IBackgroundTaskQueue, BackgroundTaskQueue>();
services.AddHostedService<QueuedHostedService>();
...

此外,您可以在配置中设置线程数 ( appsettings.json)

...
"App": {
    "MaxNumOfParallelOperations": 4
}
...
于 2020-07-13T00:23:04.830 回答