1、新建角色服務
2、nuget引用服務
Microsoft.Extensions.Hosting.WindowsServices,這個很重要不然會提示服務未響應
三、啟動頁修改程式碼引用UseWindowsService
namespace WService { public class Program { public static void Main(string[] args) { IHost host = Host.CreateDefaultBuilder(args) .UseWindowsService() .ConfigureServices(services => { services.AddHostedService<Worker>(); }) .Build(); host.Run(); } } }
四、編寫worker程式碼
using TouchSocket.Core; using TouchSocket.Http; using TouchSocket.Rpc; using TouchSocket.Sockets; using TouchSocket.WebApi; using TouchSocket.WebApi.Swagger; using Model; using WService.APIServer; using WService.Tools; using WService.Plugin; using LogLevel = Microsoft.Extensions.Logging.LogLevel; namespace WService { 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); } } public override async Task StartAsync(CancellationToken cancellationToken) { //主程式碼 } public override async Task StopAsync(CancellationToken cancellationToken) { Console.WriteLine("Service is stopping."); await base.StopAsync(cancellationToken); } } }
五、釋出和執行
會生成exe檔案
管理員方式執行CMD 建立服務 sc create WService binpath= exe檔案路徑 type= own start= auto displayname= WService 開始服務 net start WService 停止服務 net stop WService 解除安裝服務 sc delete WService