How would you implement a background task queue accepting ad-hoc work items dynamically at runtime, rather than a fixed polling loop?
Short answer
A common pattern defines an IBackgroundTaskQueue interface backed by a Channel >, with a QueueBackgroundWorkItem method that any part of the application (like a controller action) can call to enqueue arbitrary async work, while a single BackgroundService continuously dequeues…
Advertisement
AModel answer
A common pattern defines an IBackgroundTaskQueue interface backed by a Channel<Func<CancellationToken, Task>>, with a QueueBackgroundWorkItem method that any part of the application (like a controller action) can call to enqueue arbitrary async work, while a single BackgroundService continuously dequeues and executes items from the channel -- decoupling 'something needs background processing' (raised anywhere in the app) from 'how background processing actually happens' (centralized in one consumer).
public interface IBackgroundTaskQueue {
void QueueBackgroundWorkItem(Func<CancellationToken, Task> workItem);
Task<Func<CancellationToken, Task>> DequeueAsync(CancellationToken ct);
}
// Controller usage:
_taskQueue.QueueBackgroundWorkItem(async ct => await SendWelcomeEmailAsync(userId, ct));Real-world example
A user-registration endpoint enqueues a 'send welcome email' work item onto the background task queue and returns immediately to the client, with a single dedicated BackgroundService processing that (and any other queued) work item asynchronously afterward.
Likely follow-ups
- How does this pattern handle a work item that throws an exception?
- What are the durability trade-offs of an in-memory Channel-based queue versus a persistent message broker?
Related topics