前提条件 了解异步编程 使用 async 修饰符可将方法、lambda 表达式或匿名方法指定为异步。 如果对方法或表达式使用此修饰符,则其称为异步方法 。 引用微软官方文档https://docs.microso
前提条件 了解异步编程
使用 async
修饰符可将方法、lambda 表达式或匿名方法指定为异步。 如果对方法或表达式使用此修饰符,则其称为异步方法 。
引用微软官方文档 https://docs.microsoft.com/zh-cn/dotnet/csharp/programming-guide/concepts/async/
业务场景适合 定时同步或推送 数据等
一、了解 BackgroundService 抽象类结构
1 namespace Microsoft.Extensions.Hosting 2 { 3 // 4 // 摘要: 5 // Base class for implementing a long running Microsoft.Extensions.Hosting.IHostedService. 6 public abstract class BackgroundService : IHostedService, IDisposable 7 { 8 protected BackgroundService(); 9 10 // 11 // 摘要: 12 // Gets the Task that executes the background operation. 13 // 14 // 言论: 15 // Will return null if the background operation hasn't started. 16 public virtual Task ExecuteTask { get; } 17 18 public virtual void Dispose(); 19 // 20 // 摘要: 21 // Triggered when the application host is ready to start the service. 22 // 23 // 参数: 24 // cancellationToken: 25 // Indicates that the start process has been aborted. 26 public virtual Task StartAsync(CancellationToken cancellationToken); 27 // 28 // 摘要: 29 // Triggered when the application host is performing a graceful shutdown. 30 // 31 // 参数: 32 // cancellationToken: 33 // Indicates that the shutdown process should no longer be graceful. 34 public virtual Task StopAsync(CancellationToken cancellationToken); 35 // 36 // 摘要: 37 // This method is called when the Microsoft.Extensions.Hosting.IHostedService starts. 38 // The implementation should return a task that represents the lifetime of the long 39 // running operation(s) being performed. 40 // 41 // 参数: 42 // stoppingToken: 43 // Triggered when Microsoft.Extensions.Hosting.IHostedService.StopAsync(System.Threading.CancellationToken) 44 // is called. 45 // 46 // 返回结果: 47 // A System.Threading.Tasks.Task that represents the long running operations. 48 protected abstract Task ExecuteAsync(CancellationToken stoppingToken); 49 } 50 }
二、继承 BackgroundService 抽象类 实现 ExecuteAsync 执行异步方法
1 public class CustomBackgroundService : BackgroundService 2 { 3 protected override async Task ExecuteAsync(CancellationToken stoppingToken) 4 { 5 while (!stoppingToken.IsCancellationRequested) 6 { 7 8 //你的业务逻辑 9 System.Console.WriteLine($"{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff")} 自定义定时后台服务"); 10 11 await Task.Delay(2400);//延迟等待 毫秒为单位 12 } 13 } 14 }
三、Program 类注入服务
1 var builder = WebApplication.CreateBuilder(args); 2 builder.Services.AddHostedService<CustomBackgroundService>();//注入服务
四、实现效果