1 public abstract class BackGroundWork : BackgroundService 2 { 3 /// <summary> 4 /// 创建⼀个取消标记源 5 /// </summary> 6 private readonly CancellationTokenSource cancellationTokenSource = new CancellationTokenSource(); 7 /// <summary> 8 /// 入参委托 9 /// </summary> 10 private Action<object> action; 11 12 /// <summary> 13 /// 初始化 14 /// </summary> 15 protected void Init() 16 { 17 action = async (e) => 18 { 19 while (true) 20 { 21 DoWork(e); 22 await Task.Delay(TimeSpan.FromSeconds(10)); 23 } 24 }; 25 } 26 /// <summary> 27 /// 执行方法 28 /// </summary> 29 /// <param name="stoppingToken"></param> 30 /// <returns></returns> 31 protected override Task ExecuteAsync(CancellationToken stoppingToken) 32 { 33 Init(); 34 _ = Task.Factory.StartNew(action, cancellationTokenSource.Token); 35 return Task.CompletedTask; 36 } 37 /// <summary> 38 /// 停止执行方法 39 /// </summary> 40 /// <param name="cancellationToken"></param> 41 /// <returns></returns> 42 public override Task StopAsync(CancellationToken cancellationToken) 43 { 44 cancellationTokenSource.Cancel(); 45 return base.StopAsync(cancellationToken); 46 } 47 48 protected abstract void DoWork(object e); 49 50 }
public partial class SyncWorker : BackGroundWork { protected override void DoWork(object e) { var service = ServiceLocator.Instance.GetRequiredService<SyncService>(); Task.WaitAll(service.ExecServiceAsync()); } }
C# BackgroundService服务案例
可以使用三方库,hangfire, topshelf, Quartz. and so on.
标签:Task,C#,void,BackgroundService,案例,protected,override,public From: https://www.cnblogs.com/Leo_wl/p/18650088