詳解如何將.NET應(yīng)用轉(zhuǎn)換成Window服務(wù)
寫在前面
本文介紹了將.NET8.0應(yīng)用程序轉(zhuǎn)換成Windows服務(wù)。
需要在NuGet中獲取并安裝:Microsoft.Extensions.Hosting.WindowsServices 包
代碼實(shí)現(xiàn)
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); //判斷當(dāng)前系統(tǒng)是否為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); } } } }
發(fā)布配置
可以使用批處理安裝服務(wù):
@echo off @title 安裝windows服務(wù) @echo off echo= 安裝服務(wù)! @echo off @sc create worktest binPath= "%~dp0WorkerService1.exe" echo= 啟動(dòng)服務(wù)! @echo off @sc start worktest @echo off echo= 配置服務(wù)! @echo off @sc config worktest start= AUTO @echo off echo= 成功安裝、啟動(dòng)、配置服務(wù)! @pause
執(zhí)行結(jié)果
由于編碼問題,中文出現(xiàn)了亂碼,但是服務(wù)已經(jīng)成功創(chuàng)建并配置為自動(dòng)啟動(dòng)了。
到此這篇關(guān)于詳解如何將.NET應(yīng)用轉(zhuǎn)換成Window服務(wù)的文章就介紹到這了,更多相關(guān).NET應(yīng)用轉(zhuǎn)換成Window服務(wù)內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
C#實(shí)現(xiàn)模擬ATM自動(dòng)取款機(jī)功能
這篇文章介紹了C#實(shí)現(xiàn)模擬ATM自動(dòng)取款機(jī)功能的方法,文中通過示例代碼介紹的非常詳細(xì)。對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2022-08-08C#?wpf定義ViewModelBase進(jìn)行簡化屬性綁定
綁定機(jī)制是wpf的核心,也是界面獨(dú)立的根本,尤其是使用了mvvm模式,本文主要介紹了wpf如何定義ViewModelBase進(jìn)行簡化屬性綁定,需要的可以參考下2024-04-04C#中JSON轉(zhuǎn)為實(shí)體類和List以及結(jié)合使用
開發(fā)中經(jīng)常遇到將JSON字符串轉(zhuǎn)換為List的需求,下面這篇文章主要給大家介紹了關(guān)于C#中JSON轉(zhuǎn)為實(shí)體類和List以及結(jié)合使用的相關(guān)資料,文中通過代碼介紹的非常詳細(xì),需要的朋友可以參考下2024-01-01DevExpress實(shí)現(xiàn)根據(jù)行,列索引來獲取RepositoryItem的方法
這篇文章主要介紹了DevExpress實(shí)現(xiàn)根據(jù)行,列索引來獲取RepositoryItem的方法,需要的朋友可以參考下2014-08-08C#實(shí)現(xiàn)word和pdf格式互轉(zhuǎn)
這篇文章主要為大家詳細(xì)介紹了如何通過C#實(shí)現(xiàn)word和pdf格式互轉(zhuǎn)功能,文中的示例代碼講解詳細(xì),感興趣的小伙伴可以跟隨小編一起學(xué)習(xí)一下2024-10-10