• 欢迎访问搞代码网站,推荐使用最新版火狐浏览器和Chrome浏览器访问本网站!
  • 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏搞代码吧

如何在ASP.Net Core中使用 IHostedService的方法

c# 搞代码 4年前 (2022-01-09) 15次浏览 已收录 0个评论

在我们应用程序中常常会有一些执行后台任务和任务调度的需求,那如何在 ASP.Net Core 中实现呢? 可以利用 Azure WebJobs 或者其他一些第三方任务调度框架,如:Quartz 和 Hangfire。

在 ASP.Net Core 中,也可以将 后台任务 作为托管服务的模式,所谓的 托管服务 只需要实现框架中的 IHostedService 接口并囊括进你需要的业务逻辑作为后台任务,这篇文章将会讨论如何在 ASP.Net Core 中构建托管服务。

创建托管服务

要想创建托管服务,只需要实现 IHostedService 接口即可,下面就是 IHostedService 接口的声明。

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

这一节中我们在 ASP.Net Core 中做一个极简版的 托管服务, 首先自定义一个 MyFirstHostedService 托管类,代码如下:

  public class MyFirstHostedService : IHostedService
  {
    protected async override Task ExecuteAsync(CancellationToken token)
    {
      throw new NotImplementedException();
    }
  }

 

创建 BackgroundService

有一点要注意,上一节的 MyFirstHostedService 实现了 IHostedService 接口,实际开发中并不需要这样做,因为 .Net Core 中已经提供了抽象类 BackgroundService,所以接下来重写抽象类的 ExecuteAsync 方法即可,如下代码所示:

  public class MyFirstHostedService : BackgroundService
  {
    protected async override Task ExecuteAsync(CancellationToken token)
    {
      throw new NotImplementedException();
    }
  }

下面的代码片段展示了一个简单的 Log 方法,用于记录当前时间到文件中,这个方法由 托管服务 触发。

    private async Task Log()
    {
      using (StreamWriter sw = new StreamWriter(@"D:\log.txt",true))
      {
        await sw.WriteLineAsync(DateTime.Now.ToLongTimeString());
      }
    }

使用 ExecuteAsync 方法

接下来看看如何实现 ExecuteAsync 方法,这个方法的逻辑就是周期性(second/s)的调用 Log() 方法,如下代码所示:

  protected async override Task ExecuteAsync(CancellationToken token)
  {
    while (!token.IsCancellationRequested)
    {
      await Log();
      await Task.Delay(1000, token);
    }
  }

好了,下面是完整的 MyFirstHostedService 类代码,仅供参考。

using Microsoft.Extensions.Hosting;
using System;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
namespace HostedServicesApp
{
  public class MyFirstHostedService : BackgroundService
  {
    protected async override Task ExecuteAsync(CancellationToken token)
    {
      while (!token.IsCancellationRequested)
      {
        await Log();
        await Task.Delay(1000, token);
      }
    }
    private async Task Log()
    {
      u<strong style="color:transparent">本文来源gaodai#ma#com搞@@代~&码*网/</strong>sing (StreamWriter sw = new StreamWriter(@"D:\log.txt",true))
      {
        await sw.WriteLineAsync(DateTime.Now.ToLongTimeString());
      }
    }
  } 
}

托管服务注册

托管服务类已经写好了,要想注入到 Asp.NET Core 中,需要在 Startup.ConfigureServices 中将 托管服务类 注入到 ServiceCollection 中,如下代码所示:

  public void ConfigureServices(IServiceCollection services)
  {
    services.AddHostedService<MyFirstHostedService>();
    services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
  } 

搞代码网(gaodaima.com)提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发送到邮箱[email protected],我们会在看到邮件的第一时间内为您处理,或直接联系QQ:872152909。本网站采用BY-NC-SA协议进行授权
转载请注明原文链接:如何在ASP.Net Core中使用 IHostedService的方法

喜欢 (0)
[搞代码]
分享 (0)
发表我的评论
取消评论

表情 贴图 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址