在咱们应用程序中经常会有一些执行后台任务和任务调度的需要,那如何在 ASP.Net Core 中实现呢? 能够利用 Azure WebJobs 或者其余一些第三方任务调度框架,如:QuartzHangfire

在 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()        {            using (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);    } 

当把应用程序跑起来后,你会看见程序每秒都会往 D:\log.txt 文件中记录日志。

在 IHostedService 中提供的 StartAsyncStopAsync 可用于在 ASP.NET Core 中执行或进行后台任务,你能够用它在你的应用程序中更新数据或其余操作,还有这些周期性业务逻辑是跑在后盾线程中的,这样就不会导致主申请线程的阻塞。

译文链接:https://www.infoworld.com/art...

更多高质量干货:参见我的 GitHub: csharptranslate