ASP.NET Core: BackgroundService停止(StopAsync)后无法重新启动(StartAsync)的问题
这里的 BackgroundService 是指:
Microsoft.Extensions.Hosting.BackgroundService
1. 问题复现
继承该BackgroundService,实现自己的MyService :
public class MyService : BackgroundService
{
private CancellationTokenSource _CancelSource; public async Task StartAsync()
{
_CancelSource = new CancellationTokenSource();
await base.StartAsync(_CancelSource.Token);
Console.WriteLine("Start");
} public async Task CancelAsync()
{
await base.StopAsync(_CancelSource.Token);
Console.WriteLine("Stop");
} protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
while (!stoppingToken.IsCancellationRequested)
{
await Task.Delay(, stoppingToken).ContinueWith(tsk =>
{
Console.WriteLine(string.Format("{0} working...", DateTime.Now.ToString("mm:ss")));
});
}
}
}
实例化后可以启动运行,然后停止。但是再次调用该实例的 StartAsync()就启动不了了。
当然,从 BackgroundService 实现的接口(IHostedService)来看,可能这个类本身就没打算让你手动控制启停。
2. 原因
一句话概括就是
作为函数输入参数的 CancellationToken 并没有用到
这也就是难怪网上的教程都是直接使用 CancellationToken.None 作为输入参数的原因。
下面是详细分析
直接贴下 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();
}
}
}
可以看到上面 StartAsync 函数调用 ExecuteAsync 时给它赋的参数直接是一个内部的只读变量,你在外部调用 StartAsync 给它输入的参数根本就没有用到。
结果就是,调用 StopAsync 之后,_stoppingCts 触发了Cancel请求,那么 _stoppingCts.IsCancellationRequested 就变成了 true,因为是只读的,所以再次调用StartAsync 来启动,进入 ExecuteAsync 之后 while判断直接就是false跳出了。
3. 解决办法
方法一:跳过StartAsync、StopAsync ,直接调用 ExecuteAsync ;
方法二:仿照官方的 BackgroundService,实现 IHostedService 接口,自己写一个 BackgroundService
方法三:使用 BackgroundWorker
ASP.NET Core: BackgroundService停止(StopAsync)后无法重新启动(StartAsync)的问题的更多相关文章
- asp.net core 1.1 升级后,操作mysql出错的解决办法。
遇到问题 core的版本从1.0升级到1.1,操作mysql数据库,查询数据时遇到MissingMethodException问题,更新.插入操作没有问题. 如果你也遇到这个问题,请参照以下步骤进行升 ...
- ASP.NET CORE的Code Fist后Models更改了怎么办?
上次我写到MVC的code fist后,自动生成数据库并自动生成web页面了 点击打开链接 那么随着项目需求的逐步明确,model变化了怎么办呢?其实和上次一样的,有两条关键的语句要记住 Add-Mi ...
- ASP.NET Core中使用IOC三部曲(三.采用替换后的Autofac来实现AOP拦截)
前言 本文主要是详解一下在ASP.NET Core中,采用替换后的Autofac来实现AOP拦截 觉得有帮助的朋友~可以左上角点个关注,右下角点个推荐 这里就不详细的赘述IOC是什么 以及DI是什么了 ...
- ASP.NET Core 运行原理解剖[2]:Hosting补充之配置介绍
在上一章中,我们介绍了 ASP.NET Core 的启动过程,主要是对 WebHost 源码的探索.而本文则是对上文的一个补充,更加偏向于实战,详细的介绍一下我们在实际开发中需要对 Hosting 做 ...
- ASP.NET Core MVC+EF Core从开发到部署
笔记本电脑装了双系统(Windows 10和Ubuntu16.04)快半年了,平时有时间就喜欢切换到Ubuntu系统下耍耍Linux,熟悉熟悉Linux命令.Shell脚本以及Linux下的各种应用的 ...
- 系列13 docker asp.net core部署
一.介绍 本篇完整介绍asp.net core web api如何部署到docker容器中,并通过外部访问web api服务.在编写完成dockerfile之后,可以通过docker [image ...
- ASP.NET 5 改名 ASP.NET Core 1.0
今天,Scott Hanselman在其博客上宣布<ASP.NET 5 is dead - Introducing ASP.NET Core 1.0 and .NET Core 1.0>, ...
- 初识ASP.NET Core 1.0
本文将对微软下一代ASP.NET框架做个概括性介绍,方便大家进一步熟悉该框架. 在介绍ASP.NET Core 1.0之前有必要澄清一些产品名称及版本号.ASP.NET Core1.0是微软下一代AS ...
- Asp.net Core 1.0.1升级到Asp.net Core 1.1.0 Preview版本发布到Windows Server2008 R2 IIS中的各种坑
Asp.net Core 1.0.1升级到Asp.net Core 1.1.0后,程序无法运行了 解决方案:在project.json中加入runtime节点 "runtimes" ...
随机推荐
- Python小工具:3秒钟将视频转换为音频
前言 本文的文字及图片来源于网络,仅供学习.交流使用,不具有任何商业用途,版权归原作者所有,如有问题请及时联系我们以作处理. 作者: pk 哥 PS:如有需要Python学习资料的小伙伴可以加点击下方 ...
- 总结了Python中的22个基本语法
"人生苦短,我用Python".Python编程语言是最容易学习.并且功能强大的语言.只需会微信聊天.懂一点英文单词即可学会Python编程语言.但是很多人声称自己精通Python ...
- Oracle:Redhat 7.4+Oracle Rac 11.2.0.4 执行root.sh报错处理
一.报错信息 二.原因分析 因为RHEL 7使用systemd而不是initd运行进程和重启进程,而root.sh通过传统的initd运行ohasd进程 三.解决办法 在RHEL 7中ohasd需要被 ...
- 为什么要学 Python? python该怎么学
很多童鞋对为什么学习Python感到迷茫,小编来跟大家说说学习Python的10个理由,希望可以帮助到大家!!! 摘要: 看完这十个理由,我决定买本python从入门到精通! 如果你定期关注现今的科技 ...
- crm-1
1.crm 客户关系管理系统 :1.业务逻辑部分 2.权限插件 2.forms组件之modelform modelform就是model+form ,form根据model的字段生成标签 ,校验信息 ...
- 自定义Vue组件打包、发布到npm以及使用
本文将帮助:将自己写的Vue组件打包到npm进行代码托管,以及正常发布之后如何使用自己的组件. 本文讲述的仅仅是最基础的实现,其他复杂的操作需要非常熟悉webpack的相关知识,作者将继续学习. 先附 ...
- QML调用C++
//Login.h #include <QObject> #include <QDebug> class Login : public QObject { Q_OBJECT p ...
- [b0038] python 归纳 (二三)_多进程数据共享和同步_队列Queue
1 队列读写 # -*- coding: utf-8 -*- """ 多进程 共享 队列 multiprocessing.Process 逻辑: 一个进程往队列写数据, ...
- Shell命令-用户用户组管理之id、su
文件及内容处理 - id.su 1. id:查看用户的uid,gid及归属的用户组 id命令的功能说明 id 命令用于显示用户的 ID,以及所属群组的 ID.id 会显示用户以及所属群组的实际与有效I ...
- 分布式系统ID的几种生成办法
前言 一般单机或者单数据库的项目可能规模比较小,适应的场景也比较有限,平台的访问量和业务量都较小,业务ID的生成方式比较原始但是够用,它并没有给这样的系统带来问题和瓶颈,所以这种情况下我们并没有对此给 ...