aspnet core运行后台服务任务
之前在公司的一个项目中需要用到定时程序,当时使用的是aspnet core提供的IHostedService接口来实现后台定时程序,具体的示例可去官网查看。现在的dotnet core中默认封装了实现IHostedService接口的基类BackgroundService,该类实现如下:

// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System;
using System.Threading;
using System.Threading.Tasks; namespace Microsoft.Extensions.Hosting
{
/// <summary>
/// Base class for implementing a long running <see cref="IHostedService"/>.
/// </summary>
public abstract class BackgroundService : IHostedService, IDisposable
{
private Task _executingTask;
private readonly CancellationTokenSource _stoppingCts = new CancellationTokenSource(); /// <summary>
/// This method is called when the <see cref="IHostedService"/> starts. The implementation should return a task that represents
/// the lifetime of the long running operation(s) being performed.
/// </summary>
/// <param name="stoppingToken">Triggered when <see cref="IHostedService.StopAsync(CancellationToken)"/> is called.</param>
/// <returns>A <see cref="Task"/> that represents the long running operations.</returns>
protected abstract Task ExecuteAsync(CancellationToken stoppingToken); /// <summary>
/// Triggered when the application host is ready to start the service.
/// </summary>
/// <param name="cancellationToken">Indicates that the start process has been aborted.</param>
public virtual Task StartAsync(CancellationToken cancellationToken)
{
// Store the task we're executing
_executingTask = ExecuteAsync(_stoppingCts.Token); // If the task is completed then return it, this will bubble cancellation and failure to the caller
if (_executingTask.IsCompleted)
{
return _executingTask;
} // Otherwise it's running
return Task.CompletedTask;
} /// <summary>
/// Triggered when the application host is performing a graceful shutdown.
/// </summary>
/// <param name="cancellationToken">Indicates that the shutdown process should no longer be graceful.</param>
public virtual async Task StopAsync(CancellationToken cancellationToken)
{
// Stop called without start
if (_executingTask == null)
{
return;
} try
{
// Signal cancellation to the executing method
_stoppingCts.Cancel();
}
finally
{
// Wait until the task completes or the stop token triggers
await Task.WhenAny(_executingTask, Task.Delay(Timeout.Infinite, cancellationToken));
} } public virtual void Dispose()
{
_stoppingCts.Cancel();
}
}
}

根据BackgroundService源码,我们只要实现该类的抽象方法ExecuteAsync即可。
可以有两种实现方式来做定时程序,第一种就是实现一个Timer:

using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using System;
using System.IO;
using System.Threading;
using System.Threading.Tasks; namespace DemoOne.Models
{
public class TimedBackgroundService : BackgroundService
{
private readonly ILogger _logger;
private Timer _timer; public TimedBackgroundService(ILogger<TimedBackgroundService> logger)
{
_logger = logger;
} protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
_timer = new Timer(DoWork, null, TimeSpan.Zero, TimeSpan.FromSeconds(5));
_logger.LogInformation("周六!");
return Task.CompletedTask; //Console.WriteLine("MyServiceA is starting."); //stoppingToken.Register(() => File.Create($"E:\\dotnetCore\\Practice\\Practice\\{DateTime.Now.Millisecond}.txt")); //while (!stoppingToken.IsCancellationRequested)
//{
// Console.WriteLine("MyServiceA 开始执行"); // await Task.Delay(TimeSpan.FromSeconds(5), stoppingToken); // Console.WriteLine("继续执行");
//} //Console.WriteLine("MyServiceA background task is stopping.");
} private void DoWork(object state)
{
_logger.LogInformation($"Hello World! - {DateTime.Now}");
} public override void Dispose()
{
base.Dispose();
_timer?.Dispose();
}
}
}

我们看看StartAsync的源码。上面的实现方式会直接返回一个已完成的Task,这样就会直接运行StartAsync方法的if判断,那么如果我们不走if呢?那么就应该由StartAsync方法返回一个已完成的Task.
第二个即是:

using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using System;
using System.IO;
using System.Threading;
using System.Threading.Tasks; namespace DemoOne.Models
{
public class TimedBackgroundService : BackgroundService
{
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
Console.WriteLine("MyServiceA is starting."); stoppingToken.Register(() => File.Create($"E:\\dotnetCore\\Practice\\Practice\\{DateTime.Now.Millisecond}.txt")); while (!stoppingToken.IsCancellationRequested)
{
Console.WriteLine("MyServiceA 开始执行"); await Task.Delay(TimeSpan.FromSeconds(5), stoppingToken); Console.WriteLine("继续执行");
} Console.WriteLine("MyServiceA background task is stopping.");
} public override void Dispose()
{
base.Dispose();
}
}
}

最后我们将实现了BackgroundService的类注入到DI即可:
services.AddHostedService<TimedBackgroundService>();
dotnet core的Microsoft.Extensions.Hosting 组件中,充斥着类似IHostedService接口中定义的方法:StartAsync、StopAsync方法。我们注入的HostedService服务会在WebHost类中通过GetRequiredService获取到注入的定时服务。随后执行StartAsync方法开始执行。建议看看Hosting组件源码,会有很多的收获。
aspnet core运行后台服务任务的更多相关文章
- Remote System Explorer Operation总是运行后台服务,卡死eclipse
阿里云 > 教程中心 > android教程 > Remote System Explorer Operation总是运行后台服务,卡死eclipse Remote System E ...
- aspnet core运行后台任务
之前在公司的一个项目中需要用到定时程序,当时使用的是aspnet core提供的IHostedService接口来实现后台定时程序,具体的示例可去官网查看.现在的dotnet core中默认封装了实现 ...
- 【转载】Remote System Explorer Operation总是运行后台服务,卡死eclipse解决办法
原来是eclipse后台进程在远程操作,就是右下角显示的“Remote System Explorer Operation”.折腾了半天,在Stack Overflow找到答案(源地址).把解决方案翻 ...
- Remote System Explorer Operation总是运行后台服务,卡死eclipse解决办法
当你右键编辑控件的id或者其他属性时都会卡很久,发现原来是eclipse后台进程在远程操作,就是右下角显示的“Remote System Explorer Operation”.折腾了半天,在Stac ...
- ASPNETCOREAPI 跨域处理 SQL 语句拼接 多条件分页查询 ASPNET CORE 核心 通过依赖注入(注入服务)
ASPNETCOREAPI 跨域处理 AspNetCoreApi 跨域处理 如果咱们有处理过MV5 跨域问题这个问题也不大. (1)为什么会出现跨域问题: 浏览器安全限制了前端脚本跨站点的访问资源, ...
- 打造跨平台.NET Core后台服务
续之前讲的在TopShelf上部署ASP.NET Core程序,作为后台服务运行,自从.NET Core 3.0出现以后,出现了自带的Generic Host,使得自托管服务变为可能.这种方式和Top ...
- AspNet Core Api Restful +Swagger 发布IIS 实现微服务之旅 (二)
上一步我们创建好CoreApi 接下来在框架中加入 Swagger 并发布 到 IIS (1)首先点击依赖项>管理Nuget包 (2)输入 Swashbuckle.aspnetCore 比 ...
- .NET Core 中的通用主机和后台服务
简介 我们在做项目的时候, 往往要处理一些后台的任务. 一般是两种, 一种是不停的运行,比如消息队列的消费者.另一种是定时任务. 在.NET Framework + Windows环境里, 我们一般会 ...
- ASP.NET Core 6框架揭秘实例演示[21]:如何承载你的后台服务
借助 .NET提供的服务承载(Hosting)系统,我们可以将一个或者多个长时间运行的后台服务寄宿或者承载我们创建的应用中.任何需要在后台长时间运行的操作都可以定义成标准化的服务并利用该系统来承载,A ...
- ASP.NET Core 6框架揭秘实例演示[22]:如何承载你的后台服务[补充]
借助 .NET提供的服务承载(Hosting)系统,我们可以将一个或者多个长时间运行的后台服务寄宿或者承载我们创建的应用中.任何需要在后台长时间运行的操作都可以定义成标准化的服务并利用该系统来承载,A ...
随机推荐
- HDC2021技术分论坛:酷炫3D效果在瘦设备上也能实现?
作者:zhuhuanhuan,图形技术专家 随着3D技术的应用普及,越来越多的场景都能看到3D的身影,比如充电动效.3D壁纸.游戏等等,给用户带来了更有趣.更丰富的体验.要满足用户的3D体验需求,离不 ...
- 重新点亮linux 命令树————用户和用户组管理[六]
前言 简单整理一下用户和用户组管理. 正文 主要是介绍下面的命令: useradd 新建用户 userdel 删除用户 passwd 修改用户面 usermod 修改用户属性 chage 修改用户属性 ...
- MMDeploy部署实战系列【第一章】:Docker,Nvidia-docker安装
MMDeploy部署实战系列[第一章]:Docker,Nvidia-docker安装 这个系列是一个随笔,是我走过的一些路,有些地方可能不太完善.如果有那个地方没看懂,评论区问就可以,我给补充. 版权 ...
- WPF开发随笔收录-查看PDF文件
一.前言 在项目的开发过程中,涉及到查看服务器生成的pdf报告文件的查看,起初的方案是通过spire.pdf这个库来将pdf文件转换成图片,然后在进行查看.但是经常被吐槽预览不清晰,后面上网发现了一个 ...
- mybatis generator生成mapper接口后的代理类,很方便使用。
1.spring 配置: <bean id="superMapperProxy" class="com.qws.v1.daoImpl.MapperProxy&quo ...
- TiDB、OceanBase、PolarDB-X、CockroachDB二级索引写入性能测评
简介: 二级索引是关系型数据库相较于NoSQL数据库的一个关键差异.二级索引必须是强一致的,因此索引的写入需要与主键的写入放在一个事务当中,事务的性能是二级索引性能的基础.本次测试将重点关注不同分布式 ...
- 殷浩详解DDD:如何避免写流水账代码?
简介: 在日常工作中我观察到,面对老系统重构和迁移场景,有大量代码属于流水账代码,通常能看到开发在对外的API接口里直接写业务逻辑代码,或者在一个服务里大量的堆接口,导致业务逻辑实际无法收敛,接口复用 ...
- ChaosBlade:从混沌工程实验工具到混沌工程平台
简介: ChaosBlade 是阿里巴巴 2019 年开源的混沌工程项目,已加入到 CNCF Sandbox 中.起初包含面向多环境.多语言的混沌工程实验工具 chaosblade,到现在发展到面向 ...
- dotnet OpenXML 继承组合颜色的 GrpFill 属性
在 OpenXML 的颜色画刷填充,有特殊的填充是 GrpFill 属性,对应 OpenXML SDK 定义的 DocumentFormat.OpenXml.Drawing.GroupFill 类型 ...
- 通过 KoP 将 Kafka 应用迁移到 Pulsar
通过 KoP 将 Kafka 应用迁移到 Pulsar 版权声明:原文出自 https://github.com/streamnative/kop ,由 Redisant 进行整理和翻译 目录 通过 ...