A high-performance background Task/ValueTask queue
$ dotnet add package Soenneker.Utils.BackgroundQueue
Soenneker.Utils.BackgroundQueueBackgroundQueue provides an efficient way to manage background task execution in .NET applications. It helps prevent application overload by processing tasks in a controlled, asynchronous manner.
ValueTask and Task types.dotnet add package Soenneker.Utils.BackgroundQueue
Register the BackgroundQueue:
void ConfigureServices(IServiceCollection services)
{
services.AddBackgroundQueueAsSingleton();
}
await serviceProvider.WarmupAndStartBackgroundQueue(cancellationToken);
For synchronous start:
serviceProvider.WarmupAndStartBackgroundQueueSync(cancellationToken);
To stop the service:
await serviceProvider.StopBackgroundQueue(cancellationToken);
For synchronous stop:
serviceProvider.StopBackgroundQueueSync(cancellationToken);
Configure the queue length and task tracking settings in your application:
{
"Background": {
"QueueLength": 5000,
"LockCounts": false,
"Log": false
}
}
QueueLength: Defines the maximum number of tasks in the queue.LockCounts: Enables thread-safe counting of running tasks.Log: Outputs task tracking information to ILoggerTo use BackgroundQueue, you probably want to inject it via your constructor:
IBackgroundQueue _queue;
void MyClass(IBackgroundQueue queue)
{
_queue = queue;
}
ValueTaskRather than wrapping the task, you can elide it directly to avoid an extra state machine:
await _queue.QueueValueTask(_ => someValueTask(), cancellationToken);
TaskSimilarly, for Task:
await _queue.QueueTask(_ => someTask(), cancellationToken);
To ensure all queued tasks finish before proceeding:
await queue.WaitUntilEmpty(cancellationToken);
The queue tracks:
ValueTask and Task instances.To check if tasks are running:
bool isProcessing = await queueInformationUtil.IsProcessing(cancellationToken);
To get current task counts:
var (taskCount, valueTaskCount) = await queueInformationUtil.GetCountsOfProcessing(cancellationToken);