我正在使用 .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)