这里的 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)的问题的更多相关文章

  1. asp.net core 1.1 升级后,操作mysql出错的解决办法。

    遇到问题 core的版本从1.0升级到1.1,操作mysql数据库,查询数据时遇到MissingMethodException问题,更新.插入操作没有问题. 如果你也遇到这个问题,请参照以下步骤进行升 ...

  2. ASP.NET CORE的Code Fist后Models更改了怎么办?

    上次我写到MVC的code fist后,自动生成数据库并自动生成web页面了 点击打开链接 那么随着项目需求的逐步明确,model变化了怎么办呢?其实和上次一样的,有两条关键的语句要记住 Add-Mi ...

  3. ASP.NET Core中使用IOC三部曲(三.采用替换后的Autofac来实现AOP拦截)

    前言 本文主要是详解一下在ASP.NET Core中,采用替换后的Autofac来实现AOP拦截 觉得有帮助的朋友~可以左上角点个关注,右下角点个推荐 这里就不详细的赘述IOC是什么 以及DI是什么了 ...

  4. ASP.NET Core 运行原理解剖[2]:Hosting补充之配置介绍

    在上一章中,我们介绍了 ASP.NET Core 的启动过程,主要是对 WebHost 源码的探索.而本文则是对上文的一个补充,更加偏向于实战,详细的介绍一下我们在实际开发中需要对 Hosting 做 ...

  5. ASP.NET Core MVC+EF Core从开发到部署

    笔记本电脑装了双系统(Windows 10和Ubuntu16.04)快半年了,平时有时间就喜欢切换到Ubuntu系统下耍耍Linux,熟悉熟悉Linux命令.Shell脚本以及Linux下的各种应用的 ...

  6. 系列13 docker asp.net core部署

    一.介绍   本篇完整介绍asp.net core web api如何部署到docker容器中,并通过外部访问web api服务.在编写完成dockerfile之后,可以通过docker [image ...

  7. 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>, ...

  8. 初识ASP.NET Core 1.0

    本文将对微软下一代ASP.NET框架做个概括性介绍,方便大家进一步熟悉该框架. 在介绍ASP.NET Core 1.0之前有必要澄清一些产品名称及版本号.ASP.NET Core1.0是微软下一代AS ...

  9. 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" ...

随机推荐

  1. cmdb项目-3

    1. cmdb资产审计 2.stark组件使用 快速完成网站的一个组件,使用方式与django的admin系统类似 ,仅仅将model注册 ,就可以生成对model增删改查的页面 ,当然这里还包括了模 ...

  2. katalon studio升级到6.3.3版本后如何生成测试报告

    背景: katalon studio 6.3.0版本开始,默认不会生成测试报告,因此,原先自动化运行结果的邮件也就不会包含测试报告附件. 解决方法如下: 通过插件[basic reports]生成测试 ...

  3. linux 在切换用户时出现:命令提示符-bash-4.1$错误解决

    有时候在使用用户登陆Linux系统时会发现,命令行提示符成了:-bash-4.1$,不显示用户名,路径信息. 原因:用户家目录里面与环境变量有关的文件被删除所导致的 也就是这俩文件:.bash_pro ...

  4. Qt之圆角阴影边框

    Qt的主窗体要做出类似WIN7那种圆角阴影边框,这一直是美工的需求. 这里是有一些门道的,尤其是,这里藏着一个很大的秘密. 这个秘密是一个QT的至少横跨3个版本,存在了2年多的BUG... https ...

  5. IAP15W4K58S4引脚定义 STC15

  6. Android JS打开原生应用

    设置App通过网页JS,唤醒打开本地应用. 在AndroidManifest 中,在应用启动页配置下,添加android:exported="true",设置category 添加 ...

  7. 从立创EDA,Gratipay看中文编程开发环境和推广运营的一个趋势

    前不久听说立创EDA,对比之前的讨论: 适合中文用户的编程语言和IDE, 侧重于现有语言/IDE不具备的特性 · Issue #11 · program-in-chinese/overview,觉得颇 ...

  8. [前端] js中call方法的理解和思考

    最近接手前端的工作,对当前项目中自制的js框架下,js的使用产生了非常多的困惑.尤其是js的类,对象,函数,this等等相互之间的关系和转换,以前学过也忘得差不多了,现在基本相当于重新看. js中的函 ...

  9. nginx的共享字典项api(操作方法)

    nginx的共享内存,称为共享字典项,对于所有的worker进程都可见,是一种全局变量. 备注一下内容中的 [] 是 备注. 源码分析文档:https://www.codercto.com/a/948 ...

  10. fiddler---Fiddler修改数据信息

    在测试的过程中,可能我们会遇到需要修改一些数据查看请求返回内容是如何的,刚好Fiddler也可以满足我们的要求,Fiddler不仅可以抓包还可以修改包的内容 Fiddler修改数据原理 Fiddler ...