BackgroundTaskQueue.AspNetCore 1.0.0

There is a newer version of this package available.
See the version list below for details.
dotnet add package BackgroundTaskQueue.AspNetCore --version 1.0.0
                    
NuGet\Install-Package BackgroundTaskQueue.AspNetCore -Version 1.0.0
                    
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="BackgroundTaskQueue.AspNetCore" Version="1.0.0" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="BackgroundTaskQueue.AspNetCore" Version="1.0.0" />
                    
Directory.Packages.props
<PackageReference Include="BackgroundTaskQueue.AspNetCore" />
                    
Project file
For projects that support Central Package Management (CPM), copy this XML node into the solution Directory.Packages.props file to version the package.
paket add BackgroundTaskQueue.AspNetCore --version 1.0.0
                    
#r "nuget: BackgroundTaskQueue.AspNetCore, 1.0.0"
                    
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
#:package BackgroundTaskQueue.AspNetCore@1.0.0
                    
#:package directive can be used in C# file-based apps starting in .NET 10 preview 4. Copy this into a .cs file before any lines of code to reference the package.
#addin nuget:?package=BackgroundTaskQueue.AspNetCore&version=1.0.0
                    
Install as a Cake Addin
#tool nuget:?package=BackgroundTaskQueue.AspNetCore&version=1.0.0
                    
Install as a Cake Tool

BackgroundTaskQueue.AspNetCore

BackgroundTaskQueue.AspNetCore is a lightweight library that provides a robust background task queue for ASP.NET Core applications. It leverages the Task Parallel Library (TPL) Dataflow (specifically, BufferBlock and ActionBlock) to efficiently queue and process work items in the background, decoupling task production from execution.

Features

  • Asynchronous Task Offloading: Easily offload work from transient components (e.g., controllers, services) to a shared background worker.
  • Scoped Dependency Resolution: Each queued work item executes within its own DI scope, ensuring that services are correctly instantiated and disposed.
  • Controlled Concurrency: Configure the maximum degree of parallelism to limit concurrent execution.
  • Cancellation Support: Work items respect cancellation tokens, ensuring graceful shutdown of the background processing.
  • Queue Monitoring: Get insight into the current queue length.

Getting Started

Installation

Clone this repository or add the project to your solution. Then, register the service using the provided extension method.

Usage

Registering the Service

In your Program.cs or Startup.cs, register the background task queue service with optional configuration settings. The example below demonstrates how to add the service and customize options such as the maximum degree of parallelism and bounded capacity:

// In Program.cs or Startup.cs
builder.Services.AddOffloadWorkService(options =>
{
    options.MaxDegreeOfParallelism = 5; // Controls how many tasks can run concurrently
    options.BoundedCapacity = -1; // Limits the number of enqueued tasks (-1 for unlimited)
});

Default Configuration

  • MaxDegreeOfParallelism: 3 (Only three tasks run concurrently)
  • BoundedCapacity: -1 (Unlimited queue capacity)

The MaxDegreeOfParallelism setting limits the number of tasks executing simultaneously, but does not restrict the total number of tasks that can be enqueued. The BoundedCapacity setting defines the maximum number of tasks that can be queued before rejecting additional work.

Offloading Work

Inject the IOffloadWorkService into your controller or service and use it to queue work. Each work item receives the current IServiceProvider and a cancellation token, making it safe to resolve scoped services.

using Microsoft.AspNetCore.Mvc;
using AspNetCore.BackgroundTaskQueue;

[ApiController]
[Route("[controller]")]
public class WorkController : ControllerBase
{
    private readonly IOffloadWorkService _offloadWorkService;

    public WorkController(IOffloadWorkService offloadWorkService)
    {
        _offloadWorkService = offloadWorkService;
    }

    [HttpPost("do-work")]
    public IActionResult DoWork([FromQuery] string param)
    {
        // Offload a background task
        var accepted = _offloadWorkService.Offload(async (serviceProvider, myParam, cancellationToken) =>
        {
            // Resolve a service
            var myService = serviceProvider.GetRequiredService<IMyService>();

            // Execute some work asynchronously
            await myService.DoWorkAsync(myParam, cancellationToken);
        }, param);

        if (accepted)
        {
            return Accepted();
        }

        // The BoundedCapacity of the queue has been reached. Let caller know.
        return StatusCode(StatusCodes.Status429TooManyRequests, "Task queue is full.");
    }
}

Checking Queue Length

You can also retrieve the current length of the task queue for monitoring or logging purposes:

int queueLength = _offloadWorkService.GetQueueLength();

How It Works

The core of the library is the OffloadWorkService, which implements both IOffloadWorkService and IHostedService (via BackgroundService). It uses:

  • BufferBlock<Func<Task>>: Acts as the work queue. Each enqueued work item is a lambda (a Func<Task>) that encapsulates the work to be performed.
  • ActionBlock<Func<Task>>: Processes the queued work items with a configurable maximum degree of parallelism. It ensures that each task runs safely within its own dependency injection scope.
  • Cancellation Tokens: The service creates a linked cancellation token combining the ASP.NET Core host’s token and an internal token. This ensures that tasks respect shutdown signals.
  • Scoped Work Execution: Each work item is executed by first creating an AsyncServiceScope (using the injected IServiceScopeFactory), ensuring that all DI dependencies are properly resolved and disposed after use.

Contributing

Contributions are welcome! If you have improvements or bug fixes, please open an issue or submit a pull request.

License

This project is licensed under the MIT License.

Product Compatible and additional computed target framework versions.
.NET net6.0 is compatible.  net6.0-android was computed.  net6.0-ios was computed.  net6.0-maccatalyst was computed.  net6.0-macos was computed.  net6.0-tvos was computed.  net6.0-windows was computed.  net7.0 was computed.  net7.0-android was computed.  net7.0-ios was computed.  net7.0-maccatalyst was computed.  net7.0-macos was computed.  net7.0-tvos was computed.  net7.0-windows was computed.  net8.0 is compatible.  net8.0-android was computed.  net8.0-browser was computed.  net8.0-ios was computed.  net8.0-maccatalyst was computed.  net8.0-macos was computed.  net8.0-tvos was computed.  net8.0-windows was computed.  net9.0 is compatible.  net9.0-android was computed.  net9.0-browser was computed.  net9.0-ios was computed.  net9.0-maccatalyst was computed.  net9.0-macos was computed.  net9.0-tvos was computed.  net9.0-windows was computed.  net10.0 was computed.  net10.0-android was computed.  net10.0-browser was computed.  net10.0-ios was computed.  net10.0-maccatalyst was computed.  net10.0-macos was computed.  net10.0-tvos was computed.  net10.0-windows was computed. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.
  • net6.0

    • No dependencies.
  • net8.0

    • No dependencies.
  • net9.0

    • No dependencies.

NuGet packages

This package is not used by any NuGet packages.

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last Updated
2.0.1 205 3/23/2025
2.0.0 157 3/23/2025
1.0.0 150 3/17/2025