我们通常需要在应用程序中执行后台任务和计划的作业。 要在ASP.Net Core中实现后台任务,您可以利用Azure WebJobs或许多第三方任务计划程序(如Quartz或Hangfire)中的任何一个。
在ASP.Net Core中,您也可以将后台任务实现为托管服务。 托管服务是实现IHostedService接口的类,并包括用于在后台运行任务的必要代码。 本文讨论了如何在ASP.Net Core中构建托管服务。
在撰写本文时,可以免费下载Visual Studio 2019。 如果您的系统中尚未安装Visual Studio 2019的副本,则可以从Microsoft的Visual Studio下载页面下载它。
在Visual Studio中创建一个ASP.Net Core项目
首先,让我们在Visual Studio中创建一个ASP.Net Core项目。 为此,请按照下面给出的步骤在Visual Studio 2019中创建一个新的ASP.Net Core项目。
- 启动Visual Studio IDE。
- 点击“创建新项目”。
- 在“创建新项目”窗口中,从显示的模板列表中选择“ ASP.Net Core Web应用程序”。
- 点击下一步。
- 在“配置新项目”窗口中,指定新项目的名称和位置。
- 单击创建。
- 在“创建新的ASP.Net Core Web应用程序”窗口中,从顶部的下拉列表中选择.Net Core作为运行时,并选择ASP.Net Core 2.2(或更高版本)。
- 选择“ Web应用程序”作为项目模板。
- 确保未选中“启用Docker支持”和“配置HTTPS”复选框,因为我们此处将不再使用这些功能。
- 确保将身份验证设置为“无身份验证”,因为我们也不会使用身份验证。
- 单击创建。
这将在Visual Studio中创建一个新的ASP.Net Core项目。 我们将在本文的后续部分中使用该项目来构建我们的自定义托管服务。
在ASP.Net Core中创建托管服务
要创建我们的托管服务,我们将实现IHostedService接口。 这是IHostedService接口的外观:
public interface IHostedService
{
Task StartAsync(CancellationToken cancellationToken);
Task StopAsync(CancellationToken cancellationToken);
}
在本节中,我们将在ASP.Net Core中创建托管服务的简约实现。 要创建新的托管服务,请按照下列步骤操作。
- 在“解决方案资源管理器”窗口中选择项目。
- 右键单击并选择“添加->类...”
- 在“添加新项”窗口中,为该类指定一个名称(例如MyFirstHostedService)。
- 完成后,单击添加。
这将在具有“ .cs”扩展名的同名文件中创建一个名为MyFirstHostedService的新类。 现在,使用以下代码替换默认的MyFirstHostedService类。
public class MyFirstHostedService : IHostedService
{
protected async override Task
ExecuteAsync(CancellationToken token)
{
throw new NotImplementedException();
}
}
在ASP.Net Core中使用BackgroundService类
.Net Core中提供了一个名为BackgroundService的抽象帮助程序类,该类已经实现了IHostedService接口。 让我们重写代码以扩展此类。
public class MyFirstHostedService : BackgroundService
{
protected async override Task
ExecuteAsync(CancellationToken token)
{
throw new NotImplementedException();
}
}
您可以在GitHub上检查BackgroundService类的源代码 。
以下代码段说明了一种在文本文件中记录当前时间的简单方法。 该方法将从我们的托管服务中调用。
private async Task Log()
{
using (StreamWriter sw = new
StreamWriter(@"D:\log.txt",true))
{
await sw.WriteLineAsync
(DateTime.Now.ToLongTimeString());
}
}
在ASP.Net Core中使用ExecuteAsync方法
这是ExecuteAsync方法的实现。 请注意,我们上面创建的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中注册托管服务
最后,您应该在启动类中注册托管服务,如下面的代码片段所示。
public void ConfigureServices(IServiceCollection services)
{
services.AddHostedService<MyFirstHostedService>();
services.AddMvc().SetCompatibilityVersion
(CompatibilityVersion.Version_2_2);
}
现在,当您运行此ASP.Net Core应用程序时,将在指定的位置创建一个日志文件,并且当前时间将每秒记录一次。
IHostedService接口可用于启动或停止ASP.Net Core Web应用程序中的后台任务。 您可以利用此接口来实现自己的自定义托管服务,并可以根据需要取消和正常关闭。 使用托管服务的典型用例可能是执行后台任务以更新应用程序中的某些内容或数据。 将此活动卸载到后台线程将确保不阻止主请求线程。
From: https://www.infoworld.com/article/3390741/how-to-use-ihostedservice-in-aspnet-core.html