写在前面
本文介绍了将.NET8.0应用程序转换成Windows服务。
需要在NuGet中获取并安装:Microsoft.Extensions.Hosting.WindowsServices 包
代码实现
using System.Runtime.InteropServices;
using WorkerService1;
public class Program
{
public static void Main(string[] args)
{
CreateHostBuilder(args).Build().Run();
}
public static IHostBuilder CreateHostBuilder(string[] args)
{
var host = Host.CreateDefaultBuilder(args);
//判断当前系统是否为windows
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
{
host.UseWindowsService();
}
return host.ConfigureServices((hostContext, services) =>
{
services.AddHostedService<Worker>();
});
}
}
namespace WorkerService1
{
public class Worker : BackgroundService
{
private readonly ILogger<Worker> _logger;
public Worker(ILogger<Worker> logger)
{
_logger = logger;
}
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
while (!stoppingToken.IsCancellationRequested)
{
if (_logger.IsEnabled(LogLevel.Information))
{
_logger.LogInformation("Worker running at: {time}", DateTimeOffset.Now);
}
await Task.Delay(1000, stoppingToken);
}
}
}
}
发布配置
可以使用批处理安装服务:
@echo off
@title 安装windows服务
@echo off
echo= 安装服务!
@echo off
@sc create worktest binPath= "%~dp0WorkerService1.exe"
echo= 启动服务!
@echo off
@sc start worktest
@echo off
echo= 配置服务!
@echo off
@sc config worktest start= AUTO
@echo off
echo= 成功安装、启动、配置服务!
@pause
执行结果
由于编码问题,中文出现了乱码,但是服务已经成功创建并配置为自动启动了。