public abstract class InterfaceMethed : BackgroundService
{
//创建一个取消标记源
private readonly CancellationTokenSource source = new CancellationTokenSource();
//入参委托
private Action<object> action = null;
//方法初始化
protected void Init()
{
action = async a =>
{
while (true)
{
DoWork(a);
await Task.Delay(TimeSpan.FromSeconds(10));
}
};
}
//执行方法
protected override Task ExecuteAsync(CancellationToken stoppingToken)
{
Init();
_ = Task.Factory.StartNew(action, source.Token);
return Task.CompletedTask;
}
//重写关闭方法
public override Task StopAsync(CancellationToken cancellationToken)
{
source.Cancel();
return base.StopAsync(cancellationToken);
}
protected abstract void DoWork(object state);
继承InterfaceMethed写入逻辑
public class Getfriend : InterfaceMethed
{
protected override void DoWork(object state)
{
Console.WriteLine("Hellow word");
}
}
在中间件调用 services.AddHostedService<Getfriend>();