.net core開發Windows服務

原文鏈接:https://blog.csdn.net/u013710468/article/details/81318244

我們知道.net core支持console和web開發,分別叫做.net core程序和asp.net core. 

查詢.net core官方文檔,並沒有介紹編寫windows service相關的說明,一直以來以爲dotnet core不支持windows service開發,知道查看asp.net core部署文檔中提到可以部署在Windows service中,從而確定dotnet是可以開發Windows service的.

查看asp.net core的Windows宿主的源代碼Microsoft.AspNetCore.Hosting.WindowsServices,發現最終給宿主是繼承自System.ServiceProcess.ServiceBase,同時實現了OnStart以及OnStop等一些列方法.我們知道dotnet framework 中的service基類也是System.ServiceProcess.ServiceBase,所以可以試下按照傳統的dotnet framework的方法嘗試開發Windowsservice.

 

我們新建一個dotnet console程序,添加一個windows服務,取名WinService

 

默認代碼如下:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.ServiceProcess;
using System.Text;
 
namespace WindowsService.Demo
{
    partial class WinService: ServiceBase
    {
        public WinService()
        {
            InitializeComponent();
        }
 
        protected override void OnStart(string[] args)
        {
            // TODO: 在此處添加代碼以啓動服務。
        }
 
        protected override void OnStop()
        {
            // TODO: 在此處添加代碼以執行停止服務所需的關閉操作。
        }
    }
}
我們發現默認是會報dll缺失的錯誤,我們添加nuget引用System.ServiceProcess.ServiceController.

 


修改main方法,運行WinService即可.dotnet沒有提供界面畫的安裝程序,可以通過sc命令安裝服務.

sc create myservicename binpath="***.exe"

using System;
using System.ServiceProcess;
 
namespace WindowsService.Demo
{
    class Program
    {
        static void Main(string[] args)
        {
            ServiceBase[] services = new ServiceBase[] { new WinService() };
            ServiceBase.Run(services);
        }
    }
}
發佈時選擇獨立部署類型,即可生產可獨立運行大的exe程序

 


 ———————————————— 
版權聲明:本文爲CSDN博主「淮陰侯」的原創文章,遵循CC 4.0 by-sa版權協議,轉載請附上原文出處鏈接及本聲明。
原文鏈接:https://blog.csdn.net/u013710468/article/details/81318244

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章