ASP.NETCore中的托管服务和工作服务的区别及代码示例解决方法。
创始人
2024-09-18 14:00:58
0

ASP.NET Core 中有两种类型的后台服务:托管服务(Hosted Service)和工作服务(Worker Service)。它们的主要区别在于实现的接口不同。

  1. 托管服务(Hosted Service):实现 IHostedService 接口的服务,在 ASP.NET Core 应用程序启动时启动,并在应用程序关闭时停止。

以下是一个示例,演示如何实现 IHostedService 接口以创建服务:

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

public class MyHostedService : IHostedService, IDisposable
{
    private Timer _timer;

    public Task StartAsync(CancellationToken cancellationToken)
    {
        _timer = new Timer(DoWork, null, TimeSpan.Zero,
            TimeSpan.FromSeconds(5));

        return Task.CompletedTask;
    }

    private void DoWork(object state)
    {
        Console.WriteLine("Worker running at: {time}", DateTimeOffset.Now);
    }

    public Task StopAsync(CancellationToken cancellationToken)
    {
        _timer?.Change(Timeout.Infinite, 0);

        return Task.CompletedTask;
    }

    public void Dispose()
    {
        _timer?.Dispose();
    }
}

上面的代码创建了一个实现 IHostedService 接口的服务,它使用 Timer 执行一些示例工作。这个服务会在应用程序启动时启动,并每隔 5 秒输出一次消息,直到应用程序关闭时停止。

  1. 工作服务(Worker Service):实现后台服务的最新方法。它们使用 .NET Core 3.0 中引入的新的泛型主机(Generic Host)模式来启动和停止服务。

以下是一个示例,它演示如何实现 IHostedService 接口以创建一个工作服务:

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

public class MyWorkerService : BackgroundService
{
    private readonly ILogger _

相关内容

热门资讯

智星德州菠萝外挂!德扑之星的机... 智星德州菠萝外挂!德扑之星的机制,(wEpoke)素来是有挂(详细透视规律教程);小薇(透视辅助)致...
透视黑科技(WEPoke)外挂... 这是一款非常优秀的wepoke有挂 ia辅助检测软件,能够让你了解到wepoke有挂中牌率当中全部隐...
透视好牌(德扑之星猫腻)wep... 透视好牌(德扑之星猫腻)wepoke 软件(详细辅助切实教程)总是真的有挂;致您一封信;亲爱德扑之星...
微扑克辅助挂!欢乐棋牌有挂吗,... 微扑克辅助挂!欢乐棋牌有挂吗,(wePoke)竟然真的是有挂(详细辅助微扑克教程);支持2-10人实...
透视软件(wepoKE)透明挂... 这是一款非常优秀的wepoke辅助 ia辅助检测软件,能够让你了解到wepoke辅助中牌率当中全部隐...
透视透视挂(aapoker外挂... 透视透视挂(aapoker外挂)微扑克职业代打(详细辅助大神讲解)从前存在有挂;致您一封信;亲爱aa...
透视真的(wepokE)透明挂... 透视真的(wepokE)透明挂辅助挂(wepoke的确有挂)总是是有挂(详细透视规律教程);wepo...
透视私人局(德州之星有外挂)p... 透视私人局(德州之星有外挂)pokerwoeld安卓下载(详细辅助2025教程)最初真的是有挂,您好...
wepoke辅助德之星!聚星扑... wepoke辅助德之星!聚星扑克进去后怎么操作,(aapOker)原来是真的有挂(详细透视科技教程)...
透视挂(wePoke)外挂透明... 透视挂(wePoke)外挂透明挂辅助工具(wepoke的确有挂)都是有挂(详细透视总结教程);1.w...