了解 .NET 8 中的后台服务:IHostedService 和 BackgroundService

2025-06-07

了解 .NET 8 中的后台服务:IHostedService 和 BackgroundService

.NET 8 引入了强大的功能,用于管理后台任务IHostedServiceBackgroundService这些服务支持将计划任务、后台处理和定期维护任务等长时间运行的操作无缝集成到您的应用程序中。本文将探讨这些新功能,并提供实际示例来帮助您入门。您可以在我的GitHub 存储库中找到这些示例的源代码。

什么是后台服务?

.NET 中的后台服务允许您独立于主应用程序线程在后台运行任务。这对于需要连续运行或定期运行且不阻塞主应用程序流程的任务至关重要。

IHostedService界面

IHostedService接口定义了两种方法:

  • StartAsync(CancellationToken cancellationToken):应用程序主机启动时调用。
  • StopAsync(CancellationToken cancellationToken):当应用程序主机执行正常关闭时调用。

IHostedService实施示例

using System;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;

public class TimedHostedService : IHostedService, IDisposable
{
    private readonly ILogger<TimedHostedService> _logger;
    private Timer _timer;

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

    public Task StartAsync(CancellationToken cancellationToken)
    {
        _logger.LogInformation("Timed Hosted Service running.");

        _timer = new Timer(DoWork, null, TimeSpan.Zero, TimeSpan.FromSeconds(5));

        return Task.CompletedTask;
    }

    private void DoWork(object state)
    {
        _logger.LogInformation("Timed Hosted Service is working.");
    }

    public Task StopAsync(CancellationToken cancellationToken)
    {
        _logger.LogInformation("Timed Hosted Service is stopping.");

        _timer?.Change(Timeout.Infinite, 0);

        return Task.CompletedTask;
    }

    public void Dispose()
    {
        _timer?.Dispose();
    }
}
Enter fullscreen mode Exit fullscreen mode

BackgroundService班级

该类BackgroundService是一个抽象基类,用于简化后台任务的实现。它提供了一个可重写的方法:

  • ExecuteAsync(CancellationToken stoppingToken):包含后台任务的逻辑并运行直到应用程序关闭。

BackgroundService实施示例

using System;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;

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

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

    protected override async Task ExecuteAsync(CancellationToken stoppingToken)
    {
        _logger.LogInformation("Timed Background Service running.");

        while (!stoppingToken.IsCancellationRequested)
        {
            _logger.LogInformation("Timed Background Service is working.");
            await Task.Delay(TimeSpan.FromSeconds(5), stoppingToken);
        }

        _logger.LogInformation("Timed Background Service is stopping.");
    }
}
Enter fullscreen mode Exit fullscreen mode

实际用途

要在 .NET 应用程序中使用这些后台服务,你需要在依赖注入容器中注册它们。这可以在Program.cs文件中完成。

注册托管服务

using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using System.Threading.Tasks;

public class Program
{
    public static async Task Main(string[] args)
    {
        var host = Host.CreateDefaultBuilder(args)
            .ConfigureServices(services =>
            {
                services.AddHostedService<TimedHostedService>();
                services.AddHostedService<TimedBackgroundService>();
            })
            .Build();

        await host.RunAsync();
    }
}
Enter fullscreen mode Exit fullscreen mode

主要区别

  • 抽象级别

    • IHostedService:需要手动实现启动和停止逻辑。
    • BackgroundService:通过为基类提供单一方法来重写,从而简化实现。
  • 用例

    • IHostedService:适用于需要对服务生命周期进行细粒度控制的更复杂场景。
    • BackgroundService:非常适合更简单、长时间运行的任务,可以从减少样板代码中受益。

结论

.NET 8 的后台服务通过IHostedServiceBackgroundService提供了一种强大而灵活的后台任务管理方式。通过根据您的需求选择合适的抽象,您可以高效地实现和管理应用程序中的长时间运行的操作。这些新功能增强了创建响应式、可扩展且可维护的 .NET 应用程序的能力。

本指南提供了将后台服务集成到 .NET 应用程序所需的基础。对于更复杂的场景,请考虑探索 .NET 托管框架提供的其他功能和配置。

文章来源:https://dev.to/moh_moh701/understanding-background-services-in-net-8-ihostedservice-and-backgroundservice-2eoh
PREV
如何在 Github 个人资料上构建自我更新的 README 嗨👋,我是 Codeperfectplus
NEXT
根据一天中的时间设置网站的主题(无需外部库)