如何在ASP.Net Core中实现IHostedService接口以创建一个长时间运行的后台服务的长尾?
- 内容介绍
- 文章标签
- 相关推荐
本文共计1089个文字,预计阅读时间需要5分钟。
在ASP.Net Core应用中,执行后台任务和任务调度的需求很常见。以下是在ASP.Net Core中实现这一需求的方法:
1. 使用Azure WebJobs: Azure WebJobs 是一种在Azure中运行后台任务的简单方式。您可以将WebJobs集成到ASP.Net Core应用中,以执行长时间运行的任务或定期任务。
2. 使用第三方任务调度框架: - Quartz:Quartz是一个强大的开源任务调度库,支持复杂的调度逻辑。 - Hangfire:Hangfire是一个简单易用的任务队列和后台处理库,它支持多种存储后端,包括SQL Server、Redis和Memcached。
例如,使用Hangfire在ASP.Net Core中实现后台任务调度:
csharppublic class BackgroundTask{ public async Task ExecuteAsync() { // 执行后台任务逻辑 }}
public class Startup{ public void ConfigureServices(IServiceCollection services) { // 添加Hangfire服务 services.AddHangfire(config=> { config.UseSqlServerStorage(YourConnectionString); });
// 添加Hangfire的作业存储 services.AddHangfireServer(); }}
在应用程序启动时,Hangfire会自动启动后台服务器,并等待作业执行。您可以通过以下方式安排作业:
csharpvar job=new BackgroundJob();job.Enqueue(()=> job.ExecuteAsync());
或者,您可以设置定时任务:
csharpBackgroundJob.Enqueue(()=> job.ExecuteAsync()) .ScheduleAt(recurringInterval: TimeSpan.FromMinutes(10));
这样,您就可以在ASP.Net Core应用中有效地实现后台任务和任务调度了。
在我们应用程序中常常会有一些执行后台任务和任务调度的需求,那如何在 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() { 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 中提供的 StartAsync 和 StopAsync 可用于在 ASP.NET Core 中执行或停止后台任务,你可以用它在你的应用程序中更新数据或其他操作,还有这些周期性业务逻辑是跑在后台线程中的,这样就不会导致主请求线程的阻塞。
译文链接:www.infoworld.com/article/3390741/how-to-use-ihostedservice-in-aspnet-core.html
到此这篇关于如何在ASP.Net Core中使用 IHostedService的方法的文章就介绍到这了,更多相关ASP.Net Core使用 IHostedService内容请搜索易盾网络以前的文章或继续浏览下面的相关文章希望大家以后多多支持易盾网络!
本文共计1089个文字,预计阅读时间需要5分钟。
在ASP.Net Core应用中,执行后台任务和任务调度的需求很常见。以下是在ASP.Net Core中实现这一需求的方法:
1. 使用Azure WebJobs: Azure WebJobs 是一种在Azure中运行后台任务的简单方式。您可以将WebJobs集成到ASP.Net Core应用中,以执行长时间运行的任务或定期任务。
2. 使用第三方任务调度框架: - Quartz:Quartz是一个强大的开源任务调度库,支持复杂的调度逻辑。 - Hangfire:Hangfire是一个简单易用的任务队列和后台处理库,它支持多种存储后端,包括SQL Server、Redis和Memcached。
例如,使用Hangfire在ASP.Net Core中实现后台任务调度:
csharppublic class BackgroundTask{ public async Task ExecuteAsync() { // 执行后台任务逻辑 }}
public class Startup{ public void ConfigureServices(IServiceCollection services) { // 添加Hangfire服务 services.AddHangfire(config=> { config.UseSqlServerStorage(YourConnectionString); });
// 添加Hangfire的作业存储 services.AddHangfireServer(); }}
在应用程序启动时,Hangfire会自动启动后台服务器,并等待作业执行。您可以通过以下方式安排作业:
csharpvar job=new BackgroundJob();job.Enqueue(()=> job.ExecuteAsync());
或者,您可以设置定时任务:
csharpBackgroundJob.Enqueue(()=> job.ExecuteAsync()) .ScheduleAt(recurringInterval: TimeSpan.FromMinutes(10));
这样,您就可以在ASP.Net Core应用中有效地实现后台任务和任务调度了。
在我们应用程序中常常会有一些执行后台任务和任务调度的需求,那如何在 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() { 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 中提供的 StartAsync 和 StopAsync 可用于在 ASP.NET Core 中执行或停止后台任务,你可以用它在你的应用程序中更新数据或其他操作,还有这些周期性业务逻辑是跑在后台线程中的,这样就不会导致主请求线程的阻塞。
译文链接:www.infoworld.com/article/3390741/how-to-use-ihostedservice-in-aspnet-core.html
到此这篇关于如何在ASP.Net Core中使用 IHostedService的方法的文章就介绍到这了,更多相关ASP.Net Core使用 IHostedService内容请搜索易盾网络以前的文章或继续浏览下面的相关文章希望大家以后多多支持易盾网络!

