Isaac.

ASP.NET Core Background Jobs

Implement background job processing in ASP.NET Core applications.

By EMEPublished: February 18, 2025
aspnetbackground jobshangfire

A Simple Analogy

Imagine a helpful robot assistant in your kitchen. You ask it to wash dishes, clean up, or prepare ingredients while you focus on cooking. In software, background jobs are like that robot — they handle tasks behind the scenes so your app can stay fast and responsive for users.


What Are Background Jobs?

Background jobs are tasks that run outside the main request/response cycle. Instead of making users wait for slow operations (like sending emails, resizing images, or processing payments), you "queue" these jobs to run in the background.


Why Use Background Jobs?

  • Performance: Offload slow or resource-intensive work so users get instant feedback.
  • Reliability: Retry failed jobs automatically, track status, and avoid losing work.
  • Scalability: Spread work across multiple servers or workers.
  • Separation of concerns: Keep your web app focused on handling requests, not long-running tasks.

How to Implement Background Jobs in ASP.NET Core

1. Hosted Services (Built-in)

ASP.NET Core provides IHostedService for running background tasks.

public class EmailSenderService : BackgroundService
{
    protected override async Task ExecuteAsync(CancellationToken stoppingToken)
    {
        while (!stoppingToken.IsCancellationRequested)
        {
            // Check for emails to send
            await SendPendingEmailsAsync();
            await Task.Delay(TimeSpan.FromSeconds(10), stoppingToken);
        }
    }
}

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

2. Hangfire (Popular Library)

Hangfire lets you enqueue, schedule, and manage jobs with a dashboard.

Setup:

dotnet add package Hangfire
dotnet add package Hangfire.AspNetCore

Configure in Program.cs:

builder.Services.AddHangfire(x => x.UseInMemoryStorage());
builder.Services.AddHangfireServer();

var app = builder.Build();
app.UseHangfireDashboard();

Enqueue a job:

BackgroundJob.Enqueue(() => Console.WriteLine("Hello from background!"));

Schedule a job:

BackgroundJob.Schedule(() => SendReport(), TimeSpan.FromHours(1));

Recurring job:

RecurringJob.AddOrUpdate("daily-report", () => SendReport(), Cron.Daily);

Practical Examples

  • Send welcome emails after user registration
  • Generate PDF invoices asynchronously
  • Resize uploaded images in the background
  • Sync data with external APIs on a schedule
  • Clean up old records nightly

Real-World Use Cases

  • E-commerce: Send order confirmation and shipping notifications
  • Social media: Process notifications and feed updates
  • SaaS: Generate reports and analytics
  • Healthcare: Sync patient data with external systems

Best Practices

  • Use persistent storage for jobs (SQL, Redis) in production
  • Monitor job failures and retries
  • Avoid blocking the main thread — always use async
  • Secure your job dashboard (Hangfire) with authentication
  • Gracefully handle shutdown and cancellation

Related Concepts to Explore

  • Message Queues (RabbitMQ, Azure Service Bus)
  • Distributed Task Processing (MassTransit, NServiceBus)
  • Cron Expressions and Scheduling
  • Worker Services in .NET
  • Event-Driven Architecture
  • Retry Policies and Circuit Breakers
  • Serverless Background Jobs (Azure Functions, AWS Lambda)

Summary

Background jobs let your app stay fast and reliable by moving heavy work off the main thread. Whether you use built-in hosted services or a library like Hangfire, mastering background jobs is key to building scalable, user-friendly applications.