如何在ASP.Net Core中使用 IHostedService的方法
在我们应用程序中常常会有一些执行后台任务和任务调度的需求,那如何在ASP.NetCore中实现呢?可以利用AzureWebJobs或者其他一些第三方任务调度框架,如:Quartz和Hangfire。
在ASP.NetCore中,也可以将后台任务作为托管服务的模式,所谓的托管服务只需要实现框架中的IHostedService接口并囊括进你需要的业务逻辑作为后台任务,这篇文章将会讨论如何在ASP.NetCore中构建托管服务。
创建托管服务
要想创建托管服务,只需要实现IHostedService接口即可,下面就是IHostedService接口的声明。
publicinterfaceIHostedService
{
TaskStartAsync(CancellationTokencancellationToken);
TaskStopAsync(CancellationTokencancellationToken);
}
这一节中我们在ASP.NetCore中做一个极简版的托管服务,首先自定义一个MyFirstHostedService托管类,代码如下:
publicclassMyFirstHostedService:IHostedService
{
protectedasyncoverrideTaskExecuteAsync(CancellationTokentoken)
{
thrownewNotImplementedException();
}
}
创建BackgroundService
有一点要注意,上一节的MyFirstHostedService实现了IHostedService接口,实际开发中并不需要这样做,因为.NetCore中已经提供了抽象类BackgroundService,所以接下来重写抽象类的ExecuteAsync方法即可,如下代码所示:
publicclassMyFirstHostedService:BackgroundService
{
protectedasyncoverrideTaskExecuteAsync(CancellationTokentoken)
{
thrownewNotImplementedException();
}
}
下面的代码片段展示了一个简单的Log方法,用于记录当前时间到文件中,这个方法由托管服务触发。
privateasyncTaskLog()
{
using(StreamWritersw=newStreamWriter(@"D:\log.txt",true))
{
awaitsw.WriteLineAsync(DateTime.Now.ToLongTimeString());
}
}
使用ExecuteAsync方法
接下来看看如何实现ExecuteAsync方法,这个方法的逻辑就是周期性(second/s)的调用Log()方法,如下代码所示:
protectedasyncoverrideTaskExecuteAsync(CancellationTokentoken)
{
while(!token.IsCancellationRequested)
{
awaitLog();
awaitTask.Delay(1000,token);
}
}
好了,下面是完整的MyFirstHostedService类代码,仅供参考。
usingMicrosoft.Extensions.Hosting;
usingSystem;
usingSystem.IO;
usingSystem.Threading;
usingSystem.Threading.Tasks;
namespaceHostedServicesApp
{
publicclassMyFirstHostedService:BackgroundService
{
protectedasyncoverrideTaskExecuteAsync(CancellationTokentoken)
{
while(!token.IsCancellationRequested)
{
awaitLog();
awaitTask.Delay(1000,token);
}
}
privateasyncTaskLog()
{
using(StreamWritersw=newStreamWriter(@"D:\log.txt",true))
{
awaitsw.WriteLineAsync(DateTime.Now.ToLongTimeString());
}
}
}
}
托管服务注册
托管服务类已经写好了,要想注入到Asp.NETCore中,需要在Startup.ConfigureServices中将托管服务类注入到ServiceCollection中,如下代码所示:
publicvoidConfigureServices(IServiceCollectionservices)
{
services.AddHostedService();
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
}
当把应用程序跑起来后,你会看见程序每秒都会往D:\log.txt文件中记录日志。
在IHostedService中提供的StartAsync和StopAsync可用于在ASP.NETCore中执行或停止后台任务,你可以用它在你的应用程序中更新数据或其他操作,还有这些周期性业务逻辑是跑在后台线程中的,这样就不会导致主请求线程的阻塞。
译文链接:https://www.infoworld.com/article/3390741/how-to-use-ihostedservice-in-aspnet-core.html
到此这篇关于如何在ASP.NetCore中使用IHostedService的方法的文章就介绍到这了,更多相关ASP.NetCore使用IHostedService内容请搜索毛票票以前的文章或继续浏览下面的相关文章希望大家以后多多支持毛票票!