小编coc*_*ake的帖子

为什么我的后台服务立即停止?

我正在使用 .NET Core 2.2,并且我想运行长时间运行的后台任务(如旧的 Windows 服务)。我想使用Microsoft.Extensions.Hosting.BackgroundService(在Microsoft.Extensions.Hosting.Abstractions装配中)。

我的问题是我的服务立即启动和停止。我写了这个小样本来展示我所做的:

using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using System;
using System.Threading;
using System.Threading.Tasks;

namespace MyHostedService
{
    internal static class Program
    {
        private static void Main()
        {
            new HostBuilder()
                .ConfigureServices((hostContext, services) => { services.AddHostedService<MyService>(); })
                .Build()
                .RunAsync();
        }
    }
    public class MyService : BackgroundService
    {
        protected override async Task ExecuteAsync(CancellationToken stoppingToken)
        {
            int count = 0;
            while (!stoppingToken.IsCancellationRequested)
            {
                Console.WriteLine($"Hit count: {++count}, IsCancellationRequested: {stoppingToken.IsCancellationRequested}");
                await Task.Delay(TimeSpan.FromSeconds(1));
            }
            Console.WriteLine($"IsCancellationRequested: {stoppingToken.IsCancellationRequested}");
            Console.WriteLine("The end.");
        }
    } …
Run Code Online (Sandbox Code Playgroud)

c# .net-core

3
推荐指数
1
解决办法
3819
查看次数

标签 统计

.net-core ×1

c# ×1