0

I have an console application .NET core which uses Background tasks with hosted services like described here : link

I've used the code sample provided by Microsoft and added the IBackgroundTaskQueue, BackgroundTaskQueue and QueuedHostedService.

In my Startup.cs, I'm registering QueuedHostedService instance as follows:

services.AddHostedService<QueuedHostedService>();

And IBackgroundTaskQueue as follows :

services.AddSingleton<IBackgroundTaskQueue>(ctx => {
                        if (!int.TryParse(hostContext.Configuration["QueueCapacity"], out var queueCapacity))
                            queueCapacity = 100;
                        return new BackgroundTaskQueue(queueCapacity);

I use MonitorLoop like Microsoft's article, which initialize my rabbitmq server to retrieve messages :

 public void InitRabbit()
 {
    var uri = TdiRabbitServerConstants.GetServerUri(EnvironmentType.Development, ApplicationType.Translator);
    _rabbitMQService.ConnectToServerWithConsumersAsync(uri);

    _rabbitMQService.SetEventHandlerMessageAsync(Consumer_ReceivedAsync);

    _rabbitMQService.DeclareLinkOnChannel(Queues.QueueTranslatorEventNotificationResolver, null);
    _rabbitMQService.QueueSubscription(false);
}

Tasks coming from RabbitMQ event which triggered as follows :

private async Task Consumer_ReceivedAsync(object sender, DataReceived @event)
 {
        Task.Run(async  () => await ProcessNewTask(@event));
 }

Tasks are enqueued and then dequeued and executed by the QueuedHostedService. QueuedHostedService implement this example and I use dbvega solution: link

public Task StartAsync(CancellationToken cancellationToken)
        {
            _tokenSource = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);

            for (var i = 0; i < _executorsCount; i++)
            {
                var executorTask = new Task(
                    async () =>
                    {
                        while (!cancellationToken.IsCancellationRequested)
                        {
                            _logger.LogInformation("Waiting background task {i}", i);

                            var workItem =
                                await TaskQueue.DequeueAsync(cancellationToken);

                            try
                            {
                                _logger.LogInformation($"Got background task {i}, executing deliveryTag : {workItem.Item1.DeliveryTag} " + DateTime.Now.ToLongTimeString());
                                await workItem.Item2(cancellationToken, workItem.Item1);
                            }
                            catch (Exception ex)
                            {
                                _logger.LogError(ex,
                                    "Error occurred executing {WorkItem}.", nameof(workItem));
                            }
                        }
                    }, _tokenSource.Token);

                _executors[i] = executorTask;
                executorTask.Start();
            }

            return Task.CompletedTask;
        }

I'll would like to know why when I increment executorsCount, the background processing thread that will dequeue and execute the incoming tasks take same times
if executorsCount = 2 or 8 for example.

Thanks for help

Julien Martin
  • 197
  • 2
  • 15

0 Answers0