使用.NET 6.0创建Worker Service服务程序,并注册Windows服务程序
Posted 加班写Bug
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了使用.NET 6.0创建Worker Service服务程序,并注册Windows服务程序相关的知识,希望对你有一定的参考价值。
- program
IHost host = Host.CreateDefaultBuilder(args) .UseWindowsService(options => //服务进行命名,会显示在Windows服务中的服务名称上 options.ServiceName = "H"; ).ConfigureServices(services => services.AddHostedService<Worker>(); services.AddLogging(); ).ConfigureLogging(logging => //记录日志 logging.AddNLog("NLog.config"); ) .Build();
-
Worker类
包含一些tcp通讯的逻辑 主要创建服务方法如此 相关功能按需修改
public class Worker : BackgroundService private readonly ILogger<Worker> _logger; private IConfiguration _configuration; MyTcpClient tcpClient = MyTcpClient.getInstance(); public Worker(ILogger<Worker> logger, IConfiguration configuration) _configuration = configuration; _logger = logger; tcpClient.Port = _configuration["SocketServer:Port"]; tcpClient.Address = _configuration["SocketServer:IP"]; _logger.LogInformation($"当前客户端 _configuration["SocketServer:ClientId"] 配置:ServerIp:_configuration["SocketServer:IP"]:_configuration["SocketServer:Port"]"); tcpClient.Connect(); tcpClient.AsyncOperation = AsyncOperationManager.CreateOperation(null); tcpClient.Receive += TcpClient_Receive; //tcpClient.StartConnect(); private void TcpClient_Receive(object? sender, TEventArgs<string> e) _logger.LogInformation(e.Result.ToString()); var GSProcess = new GSProcess(); _logger.LogInformation(JsonConvert.SerializeObject(GSProcess.GetAllProcess())); //GSProcess.Kill(); /// <summary> /// 服务启动时执行的操作 /// </summary> /// <param name="cancellationToken"></param> /// <returns></returns> public override async Task StartAsync(CancellationToken cancellationToken) _logger.LogInformation("Worker StartAsync at: time", DateTimeOffset.Now); await base.StartAsync(cancellationToken); /// <summary> /// 服务运行时执行的操作 /// </summary> /// <param name="stoppingToken"></param> /// <returns></returns> protected override async Task ExecuteAsync(CancellationToken stoppingToken) //while (!stoppingToken.IsCancellationRequested) // // //_logger.LogInformation("Worker running at: time", DateTimeOffset.Now); // await Task.Delay(1000, stoppingToken); // /// <summary> /// 服务停止时执行的操作 /// </summary> /// <param name="cancellationToken"></param> /// <returns></returns> public override async Task StopAsync(CancellationToken cancellationToken) tcpClient.Stop(); _logger.LogInformation("Worker StopAsync at: time", DateTimeOffset.Now); await base.StopAsync(cancellationToken); /// <summary> /// 运行时执行的方法 /// </summary> /// <param name="stoppingToken"></param> /// <returns></returns> private Task ServiceRunningMethod(CancellationToken stoppingToken) return Task.Run(() => , stoppingToken);
- 添加进服务
可以手扣命令 或者使用NSSM软件
相关介绍 https://juejin.cn/post/6981055330964733989
以上是关于使用.NET 6.0创建Worker Service服务程序,并注册Windows服务程序的主要内容,如果未能解决你的问题,请参考以下文章
[翻译] 使用 .NET Core 3.0 创建一个 Windows 服务
.net core 5 worker 服务的无密码连接字符串