Hosted Services & Background Tasks in ASP.NET Core

>

๐Ÿ’ก Concept Name

Hosted Services & Background Tasks in ASP.NET Core

๐Ÿ“˜ Quick Intro

Hosted services are long-running background tasks in ASP.NET Core apps. You register them using `IHostedService` or `BackgroundService`. They're ideal for scheduled jobs, queues, and background processing.

๐Ÿง  Analogy / Short Story

Imagine your app is a restaurant. The front desk (controllers) serves customers, but cleaning staff (hosted services) work in the background. They start with the restaurant and work quietly behind the scenes, ensuring everything runs smoothly.

๐Ÿ”ง Technical Explanation

ASP.NET Core apps can host background services using the `IHostedService` interface or by extending the `BackgroundService` class.

These services are started automatically when the app starts and can be used to run continuous or periodic background work.

You register them using `services.AddHostedService()` in `Program.cs`.

๐ŸŽฏ Purpose & Use Case

  • โœ… Schedule recurring background jobs (cron-style)
  • โœ… Process queues or messages asynchronously
  • โœ… Monitor services or API health regularly
  • โœ… Perform batch processing or report generation
  • โœ… Long-running computation without blocking UI threads

๐Ÿ’ป Real Code Example

// Sample Hosted Service
public class DailyJobService : BackgroundService
{
    protected override async Task ExecuteAsync(CancellationToken stoppingToken)
    {
        while (!stoppingToken.IsCancellationRequested)
        {
            Console.WriteLine("Running job at: " + DateTime.Now);
            await Task.Delay(TimeSpan.FromHours(24), stoppingToken);
        }
    }
}

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

โ“ Interview Q&A

Q1: What interface must a hosted service implement?
A: `IHostedService`

Q2: What's the preferred base class for background jobs?
A: `BackgroundService`

Q3: How are hosted services registered?
A: Using `AddHostedService()`

Q4: Are hosted services thread-blocking?
A: No, they're asynchronous and non-blocking.

Q5: How do you gracefully stop a service?
A: Use the `CancellationToken` passed to `ExecuteAsync()`.

Q6: Can multiple hosted services run in one app?
A: Yes, you can register multiple.

Q7: What lifecycle method starts a hosted service?
A: `StartAsync()`

Q8: What about stopping it?
A: `StopAsync()`

Q9: Can hosted services depend on DI services?
A: Yes, they support constructor injection.

Q10: Where can you see logs of background services?
A: Through `ILogger` injected into the service.

๐Ÿ“ MCQs

Q1: What interface is required for a hosted service?

  • A. IStartup
  • B. IService
  • C. IRunAsync
  • D. IHostedService

Q2: Which method runs continuously in `BackgroundService`?

  • A. ExecuteAsync()
  • B. StartLoop()
  • C. BeginAsync()
  • D. RunProcess()

Q3: What method is used to stop a hosted service?

  • A. StopAsync()
  • B. EndService()
  • C. Cancel()
  • D. Dispose()

Q4: How do you inject a scoped service into a hosted service?

  • A. Using constructor
  • B. Register in Program.cs
  • C. Using static service locator
  • D. Create scope using IServiceScopeFactory

Q5: When does a hosted service start in ASP.NET Core lifecycle?

  • A. Before middleware loads
  • B. After routing setup
  • C. After the application starts
  • D. During DI configuration

Q6: Which of the following is NOT a valid use case for hosted services?

  • A. Background email sender
  • B. Real-time chat UI rendering
  • C. Static file middleware
  • D. Scheduled report generator

Q7: What happens if a hosted service throws an unhandled exception?

  • A. It restarts automatically
  • B. It may crash the app unless handled
  • C. It retries automatically
  • D. Nothing happens

Q8: Which namespace contains `BackgroundService`?

  • A. System.Threading
  • B. Microsoft.Extensions.Hosting
  • C. Microsoft.AspNetCore.Hosting
  • D. System.Hosting

Q9: What return type does `ExecuteAsync()` use?

  • A. void
  • B. bool
  • C. Task
  • D. Task<bool>

Q10: What attribute can you use to schedule tasks in production-ready hosted services?

  • A. [Schedule]
  • B. [Timer]
  • C. [Execute]
  • D. None - you must use `Task.Delay()` or 3rd-party libraries like Quartz.NET

๐Ÿ’ก Bonus Insight

You can combine `Channel` with hosted services to build powerful producer-consumer queues in .NET Core for background task handling.

๐Ÿ“„ PDF Download

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

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

Tags: