Using BackgroundService in ASP.NET Core

๐Ÿ’ก Concept Name

BackgroundService in ASP.NET Core

๐Ÿ“˜ Quick Intro

BackgroundService is an abstract base class in ASP.NET Core that allows you to run long-running tasks on a separate thread, independent of HTTP requests.

๐Ÿง  Analogy / Short Story

Imagine a restaurant that needs to bake bread every morning. Rather than tying up the waiters, a dedicated baker (background service) quietly works behind the scenes, making fresh bread for the day ahead โ€” always running, but not interrupting the main business.

๐Ÿ”ง Technical Explanation

  • ๐Ÿงต Inherits from BackgroundService (from Microsoft.Extensions.Hosting).
  • ๐Ÿ” Executes background logic inside the overridden ExecuteAsync() method.
  • ๐Ÿ›  Can be registered in Startup.cs or Program.cs using services.AddHostedService<T>().
  • โฑ Suitable for polling, scheduled jobs, messaging, cleanup tasks, etc.
  • โŒ Should not use for UI-based operations or logic tied directly to HTTP requests.

๐ŸŽฏ Purpose & Use Case

  • โœ… Periodic data cleanup or archiving.
  • โœ… Polling external APIs.
  • โœ… Queue processing (e.g., background emails or SMS sending).
  • โœ… Background health monitoring.

๐Ÿ’ป Real Code Example

Simple background service that logs a message every 10 seconds:

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(10000, stoppingToken);
        }
    }
}

// Register in Program.cs
builder.Services.AddHostedService<WorkerService>();

โ“ Interview Q&A

Q1: What is BackgroundService?
A: A base class for implementing long-running background tasks in ASP.NET Core.

Q2: Which method must you override in BackgroundService?
A: ExecuteAsync().

Q3: Where is a BackgroundService registered?
A: In the DI container using AddHostedService<T>().

Q4: Is it tied to HTTP requests?
A: No, it runs independently.

Q5: Can BackgroundService be used for scheduled jobs?
A: Yes, using Task.Delay() or third-party schedulers like Quartz.NET.

๐Ÿ“ MCQs

Q1. What is BackgroundService in ASP.NET Core?

  • A controller
  • A middleware
  • A base class for long-running background tasks
  • A static method

Q2. Which method is overridden in BackgroundService?

  • Main
  • Configure
  • Execute
  • ExecuteAsync

Q3. How do you register a BackgroundService?

  • app.UseBackground()
  • AddSingleton()
  • services.AddHostedService
  • AddController()

Q4. Does BackgroundService run on a separate thread?

  • No
  • Yes
  • Only in dev mode
  • Only when idle

Q5. Is BackgroundService tied to user requests?

  • Yes
  • No
  • Only GET requests
  • Only POST requests

๐Ÿ’ก Bonus Insight

For more advanced scheduling, consider integrating Quartz.NET or Hangfire for cron-based or queue-backed background jobs. Also, avoid blocking operations inside ExecuteAsync to keep the app responsive.

๐Ÿ“„ PDF Download

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

โฌ… Previous:

๐Ÿ’ฌ Feedback
๐Ÿš€ Start Learning
Share:

Tags: