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());
_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(), 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运行后台任务的更多相关文章
- Core开发-后台任务利器Hangfire使用
Core开发-后台任务利器Hangfire使用 ASP.NET Core开发系列之后台任务利器Hangfire 使用. Hangfire 是一款强大的.NET开源后台任务利器,无需Windows服务/ ...
- ASP.NET Core 运行原理解剖[2]:Hosting补充之配置介绍
在上一章中,我们介绍了 ASP.NET Core 的启动过程,主要是对 WebHost 源码的探索.而本文则是对上文的一个补充,更加偏向于实战,详细的介绍一下我们在实际开发中需要对 Hosting 做 ...
- ASP.NET Core 运行原理解剖[5]:Authentication
在现代应用程序中,认证已不再是简单的将用户凭证保存在浏览器中,而要适应多种场景,如App,WebAPI,第三方登录等等.在 ASP.NET 4.x 时代的Windows认证和Forms认证已无法满足现 ...
- AspNet Core 初步认识
Core 的出现对我我没有很大的影响,当时在Core要发布的时候听到周围的人再聊再谈,我没有去太多关注,就是一个屌丝开发人员. 直到又一次偶然见到一位特别喜欢.net的老开发人员谈起Core时落泪了, ...
- AspNet Core Api Restful +Swagger 发布IIS 实现微服务之旅 (二)
上一步我们创建好CoreApi 接下来在框架中加入 Swagger 并发布 到 IIS (1)首先点击依赖项>管理Nuget包 (2)输入 Swashbuckle.aspnetCore 比 ...
- AspNet Core Api Restful +Swagger 发布IIS
上一步我们创建好CoreApi 接下来在框架中加入 Swagger 并发布 到 IIS (1)首先点击依赖项>管理Nuget包 (2)输入 Swashbuckle.aspnetCore 比 ...
- Cookies 初识 Dotnetspider EF 6.x、EF Core实现dynamic动态查询和EF Core注入多个上下文实例池你知道有什么问题? EntityFramework Core 运行dotnet ef命令迁移背后本质是什么?(EF Core迁移原理)
Cookies 1.创建HttpCookies Cookie=new HttpCookies("CookieName");2.添加内容Cookie.Values.Add(&qu ...
- 设计模式(一)单例模式:创建模式 ASPNET CORE WEB 应用程序的启动 当项目中 没有STARTUP.CS 类如何设置启动 配置等等
设计模式(一)单例模式:创建模式 先聊一下关于设计的几个原则(1)单一原则(SRP):一个类应该仅有一个引起它变化的原因 :意思就是 (一个类,最好只负责一件事情,并且只有一个引起它变化的原因(2)开 ...
- ASPNETCOREAPI 跨域处理 SQL 语句拼接 多条件分页查询 ASPNET CORE 核心 通过依赖注入(注入服务)
ASPNETCOREAPI 跨域处理 AspNetCoreApi 跨域处理 如果咱们有处理过MV5 跨域问题这个问题也不大. (1)为什么会出现跨域问题: 浏览器安全限制了前端脚本跨站点的访问资源, ...
随机推荐
- BSGS算法
BSGS算法 我是看着\(ppl\)的博客学的,您可以先访问\(ppl\)的博客 Part1 BSGS算法 求解关于\(x\)的方程 \[y^x=z(mod\ p)\] 其中\((y,p)=1\) 做 ...
- pytest 10 skip跳过测试用例
pytest.mark.skip可以标记无法在某些平台上运行的测试功能,或者你希望失败的测试功能 skip意味着只有在满足某些条件时才希望测试通过,否则pytest应该跳过运行测试.常见事例时非win ...
- linux线程(一)
线程的优先级无法保障线程的执行次序.只不过优先级高的线程获取 CPU 资源的概率大一点而已. 线程相关函数(1)-pthread_create(), pthread_join(), pthread_e ...
- python中的装饰器迭代器生成器
装饰器: 定义:本质是函数(装饰其它函数) 为其它函数添加附加功能 原则: 1 不能修改被装饰函数源代码 2 不修改被装饰函数调用方式 实现装饰器知识储备: 1 函数即‘’变量‘’ 2 高阶函数 ...
- 主机管理+堡垒机系统开发:strace命令及日志解析(五)
一.strace命令简介 测试命令截图 第一个窗口执行命令如下 [root@elk ~]# w 16:51:56 up 3 days, 6:01, 3 users, load average: 0.0 ...
- Mac 终端美化方法
美化终端,主要是主题,字体,命令行提示3个方面. 主题 使用的主题是Solarized Dark主题. 安装主题: git clone git://github.com/altercation/sol ...
- ACM-ICPC 2018 徐州赛区网络预赛 F Features Track(STL模拟)
https://nanti.jisuanke.com/t/31458 题意 有N个帧,每帧有K个动作特征,每个特征用一个向量表示(x,y).两个特征相同当且仅当他们在不同的帧中出现且向量的两个分量分别 ...
- LINQ to SQL 的常见异常及解决办法
Ø 简介 本文主要介绍 LINQ to SQL 中常见的异常,以及对应的解决办法.包括以下内容: 1. 左连接情况下,右表非空类型字段可能抛出异常 1. 左连接情况下,右表非空类型字段可能抛 ...
- Django之restframework
启动流程:引入rest_framework APP 在restframework中,GET数据可以通过request.query_params.get(xxx)获取,post数据可以通过request ...
- 小程序生成海报图片(或者原有的)并下载,&&相册授权&&按钮拉起二次授权
这是自己做小程序生成推广海报,并保存到本地相册的方法,向后台发起请求,返回一个海报图片,下载保存到相册, 如果只是单纯的下载图片代码43行-63行就足够了 如果想直接保存到相册,则不要做downFil ...