惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

腾讯CDC
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
P
Proofpoint News Feed
D
DataBreaches.Net
D
Docker
云风的 BLOG
云风的 BLOG
大猫的无限游戏
大猫的无限游戏
月光博客
月光博客
J
Java Code Geeks
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
罗磊的独立博客
Martin Fowler
Martin Fowler
U
Unit 42
Engineering at Meta
Engineering at Meta
IT之家
IT之家
Vercel News
Vercel News
B
Blog RSS Feed
人人都是产品经理
人人都是产品经理
博客园 - Franky
博客园 - 【当耐特】
Stack Overflow Blog
Stack Overflow Blog
G
Google Developers Blog
MongoDB | Blog
MongoDB | Blog

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant
Background Services in .NET — IHostedService and Backgrou...
Libin Tom Ba · 2026-04-27 · via DEV Community
Cover image for Background Services in .NET — IHostedService and BackgroundService Explained

Libin Tom Baby

IHostedService, BackgroundService, Worker Service, scoped services in background, Hangfire comparison

Not all work in a .NET application happens within an HTTP request.

Scheduled jobs, message queue consumers, cache warmers, health check pollers — these all run in the background, independently of the request pipeline.


IHostedService — The Foundation

IHostedService tells the .NET host: "run this when the application starts, stop it when the application stops."

public interface IHostedService
{
    Task StartAsync(CancellationToken cancellationToken);
    Task StopAsync(CancellationToken cancellationToken);
}

Enter fullscreen mode Exit fullscreen mode

Basic implementation

public class StartupCacheWarmer : IHostedService
{
    private readonly IProductCache _cache;
    private readonly ILogger<StartupCacheWarmer> _logger;

    public StartupCacheWarmer(IProductCache cache, ILogger<StartupCacheWarmer> logger)
    {
        _cache = cache;
        _logger = logger;
    }

    public async Task StartAsync(CancellationToken ct)
    {
        _logger.LogInformation("Warming cache...");
        await _cache.LoadAsync(ct);
        _logger.LogInformation("Cache ready.");
    }

    public Task StopAsync(CancellationToken ct) => Task.CompletedTask;
}

// Register
builder.Services.AddHostedService<StartupCacheWarmer>();

Enter fullscreen mode Exit fullscreen mode


BackgroundService — For Long-Running Work

BackgroundService is an abstract base class for long-running background tasks. Override ExecuteAsync.

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

    public OrderProcessor(ILogger<OrderProcessor> logger) => _logger = logger;

    protected override async Task ExecuteAsync(CancellationToken stoppingToken)
    {
        _logger.LogInformation("Order processor started.");

        while (!stoppingToken.IsCancellationRequested)
        {
            try
            {
                await ProcessPendingOrdersAsync(stoppingToken);
                await Task.Delay(TimeSpan.FromSeconds(30), stoppingToken);
            }
            catch (OperationCanceledException)
            {
                // Graceful shutdown — expected
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Error processing orders.");
                await Task.Delay(TimeSpan.FromSeconds(5), stoppingToken); // Back off
            }
        }

        _logger.LogInformation("Order processor stopped.");
    }

    private async Task ProcessPendingOrdersAsync(CancellationToken ct) { }
}

Enter fullscreen mode Exit fullscreen mode


Using DI Inside Background Services

Background services are registered as singletons.

You cannot directly inject scoped services (like DbContext) into a singleton.

The solution: IServiceScopeFactory

public class ReportGenerator : BackgroundService
{
    private readonly IServiceScopeFactory _scopeFactory;

    public ReportGenerator(IServiceScopeFactory scopeFactory)
        => _scopeFactory = scopeFactory;

    protected override async Task ExecuteAsync(CancellationToken ct)
    {
        while (!ct.IsCancellationRequested)
        {
            await GenerateReportsAsync(ct);
            await Task.Delay(TimeSpan.FromHours(1), ct);
        }
    }

    private async Task GenerateReportsAsync(CancellationToken ct)
    {
        // Create a new scope for each execution
        using var scope = _scopeFactory.CreateScope();
        var db = scope.ServiceProvider.GetRequiredService<AppDbContext>();
        var emailService = scope.ServiceProvider.GetRequiredService<IEmailService>();

        var orders = await db.Orders.Where(o => !o.Reported).ToListAsync(ct);
        await emailService.SendReportAsync(orders);

        foreach (var order in orders) order.Reported = true;
        await db.SaveChangesAsync(ct);
    }
}

Enter fullscreen mode Exit fullscreen mode

Create a new scope for each unit of work. The DbContext is properly scoped and disposed.


Consuming a Message Queue

public class OrderEventConsumer : BackgroundService
{
    private readonly IServiceBusClient _bus;
    private readonly IServiceScopeFactory _scopeFactory;

    public OrderEventConsumer(IServiceBusClient bus, IServiceScopeFactory scopeFactory)
    {
        _bus = bus;
        _scopeFactory = scopeFactory;
    }

    protected override async Task ExecuteAsync(CancellationToken ct)
    {
        await foreach (var message in _bus.ReadMessagesAsync(ct))
        {
            using var scope = _scopeFactory.CreateScope();
            var handler = scope.ServiceProvider.GetRequiredService<IOrderEventHandler>();
            await handler.HandleAsync(message, ct);
        }
    }
}

Enter fullscreen mode Exit fullscreen mode


When to Use Hangfire or Quartz.NET

BackgroundService is great for continuous loops and simple scheduling.

Hangfire

// One-off job
BackgroundJob.Enqueue(() => Console.WriteLine("Hello from background"));

// Recurring job
RecurringJob.AddOrUpdate("daily-report", () => SendDailyReport(), Cron.Daily);

Enter fullscreen mode Exit fullscreen mode

Hangfire persists jobs to a database — jobs survive application restarts.

Quartz.NET

More powerful scheduling: cron expressions, job dependencies, misfire handling, clustering.

var trigger = TriggerBuilder.Create()
    .WithCronSchedule("0 0 8 * * ?") // Every day at 8am
    .Build();

Enter fullscreen mode Exit fullscreen mode

Decision guide

Scenario Use
Continuous loop (poll queue, process stream) BackgroundService
Simple recurring task BackgroundService
Scheduled jobs that survive restarts Hangfire
Complex cron scheduling Quartz.NET
Distributed job coordination Hangfire or Quartz with clustering

Interview-Ready Summary

  • IHostedService = runs on app start, stops on app stop — good for one-off startup tasks
  • BackgroundService = abstract base for long-running loops — override ExecuteAsync
  • Always respect CancellationToken — check stoppingToken.IsCancellationRequested
  • Background services are singletons — never inject scoped services directly
  • Use IServiceScopeFactory to resolve scoped services within background work
  • Hangfire = persistent jobs, survive restarts, dashboard included
  • Quartz.NET = advanced cron scheduling, distributed clustering

A strong interview answer:

"BackgroundService is the built-in way to run long-running background work in .NET. You override ExecuteAsync and loop with a CancellationToken for graceful shutdown. The main gotcha is DI lifetime — background services are singletons, so you need IServiceScopeFactory to resolve scoped services like DbContext. For more complex scheduling needs — like jobs that survive restarts or complex cron expressions — Hangfire or Quartz.NET are better choices."