Implementing Background Work in ASP.NET Core

πŸ’‘ Concept Name

IHostedService / BackgroundService Pattern

πŸ“˜ Quick Intro

ASP.NET Core supports background tasks using the `IHostedService` or `BackgroundService` interfaces. These services are started when the application launches and run in the background, independent of HTTP requests.

🧠 Analogy / Short Story

Imagine a web app as a coffee shop. The HTTP requests are customer orders. But behind the scenes, you have a dishwasher that runs continuouslyβ€”quietly cleaning up, independent of customer interactions. That’s your `BackgroundService`β€”doing essential work behind the curtain.

πŸ”§ Technical Explanation

  • πŸ” IHostedService: Interface to manage background task lifecycle (start/stop).
  • πŸ“¦ BackgroundService: Abstract base class implementing IHostedService with a `ExecuteAsync()` method.
  • ⏲️ Runs independently of HTTP pipeline, useful for polling, message queues, or scheduled work.
  • 🧡 Tasks run on background threads with graceful shutdown support via `CancellationToken`.
  • πŸ›‘οΈ Automatically managed by ASP.NET Core's built-in DI system.

🎯 Purpose & Use Case

  • βœ… Queue processing (e.g., RabbitMQ, Azure Service Bus).
  • βœ… Background file cleanup or report generation.
  • βœ… Scheduled tasks using timers or CRON-like logic.
  • βœ… Heartbeat monitoring or health checks.

πŸ’» Real Code Example

Here’s a simple implementation using BackgroundService:

public class WorkerService : BackgroundService
{
    private readonly ILogger<WorkerService> _logger;

    public WorkerService(ILogger<WorkerService> logger)
    {
        _logger = logger;
    }

    protected override async Task ExecuteAsync(CancellationToken stoppingToken)
    {
        while (!stoppingToken.IsCancellationRequested)
        {
            _logger.LogInformation("Background task running at: {time}", DateTimeOffset.Now);
            await Task.Delay(5000, stoppingToken);
        }
    }
}

// In Program.cs or Startup.cs
builder.Services.AddHostedService<WorkerService>();

❓ Interview Q&A

Q1: How do you implement a background task in ASP.NET Core?
A: Use IHostedService or BackgroundService.

Q2: What’s the difference between IHostedService and BackgroundService?
A: BackgroundService is an abstract class simplifying IHostedService with an ExecuteAsync method.

Q3: Are background services tied to HTTP requests?
A: No, they run independently of HTTP pipelines.

Q4: How do you stop a background task gracefully?
A: Use the CancellationToken passed to ExecuteAsync.

Q5: Where do you register background services?
A: In `Program.cs` using `builder.Services.AddHostedService<>()`.

πŸ“ MCQs

Q1. Which interface is used for background work in ASP.NET Core?

  • IDisposable
  • IStartupFilter
  • IHostedService
  • IWebHost

Q2. What method must you override in BackgroundService?

  • Run
  • Start
  • Execute
  • ExecuteAsync

Q3. How are background services registered?

  • AddTransient
  • AddScoped
  • UseMiddleware
  • AddHostedService&lt;T&gt;()

Q4. Do background services block HTTP requests?

  • Yes
  • Sometimes
  • No
  • Only in Development

Q5. What is passed to support graceful shutdown?

  • TaskCompletionSource
  • HttpContext
  • ILogger
  • CancellationToken

πŸ’‘ Bonus Insight

While BackgroundService is best for continuous or polling tasks, consider using libraries like Hangfire, Quartz.NET, or Worker Services for complex scheduling or job persistence needs.

πŸ“„ PDF Download

Need a handy summary for your notes? Download this topic as a PDF!

➑️ Next:

πŸ’¬ Feedback
πŸš€ Start Learning
Share:

Tags: