狠狠色丁香婷婷综合尤物/久久精品综合一区二区三区/中国有色金属学报/国产日韩欧美在线观看 - 国产一区二区三区四区五区tv

LOGO OA教程 ERP教程 模切知識(shí)交流 PMS教程 CRM教程 開發(fā)文檔 其他文檔  
 
網(wǎng)站管理員

C#如何創(chuàng)建與部署Windows服務(wù)的方式


2024年6月7日 10:0 本文熱度 1181

前言

Windows 服務(wù)是運(yùn)行在后臺(tái)的應(yīng)用程序,可以設(shè)置其在系統(tǒng)啟動(dòng)時(shí)自動(dòng)運(yùn)行,并在系統(tǒng)運(yùn)行期間持續(xù)運(yùn)行。這種應(yīng)用程序沒有用戶界面,也不產(chǎn)生可視輸出。通過服務(wù)控制管理器進(jìn)行終止、暫停、啟動(dòng)的管理。本文將介紹派生自ServiceBase類的方式創(chuàng)建與部署Windows服務(wù)內(nèi)容。

ServiceBase類

ServiceBase類是服務(wù)應(yīng)用程序定義服務(wù)類時(shí)將繼承自此類。使用【W(wǎng)indows服務(wù)(.NET Framework)】項(xiàng)目模板創(chuàng)建服務(wù)應(yīng)用程序,就會(huì)創(chuàng)建繼承自此ServiceBase類的Service1類。實(shí)現(xiàn)的任何服務(wù)都必須重寫 OnStart 與 OnStop二個(gè)方法,可以重寫OnPause和OnContinue二個(gè)方法。

1、創(chuàng)建服務(wù)應(yīng)用項(xiàng)目

創(chuàng)建新項(xiàng)目----》選擇【W(wǎng)indows 服務(wù)(.NET Framework) 】

配置新項(xiàng)目的項(xiàng)目名稱、存儲(chǔ)目錄和選擇使用的目標(biāo)框架。示例使用【Fountain.ServiceHost.Worker】為項(xiàng)目名稱和解決方案名稱。

項(xiàng)目創(chuàng)建成功后,我們會(huì)看到創(chuàng)建了Service1和Program二個(gè)類。可以根據(jù)實(shí)際需要對(duì)Service1類進(jìn)行重命名。
程序入口代碼:
using System.ServiceProcess;namespace Fountain.ServiceHost.AutoWorker{    internal static class Program    {        /// <summary>        /// 應(yīng)用程序的主入口點(diǎn)。        /// </summary>        static void Main()        {            ServiceBase[] ServicesToRun;            ServicesToRun = new ServiceBase[]            {                new ServiceLog()            };            ServiceBase.Run(ServicesToRun);        }    }}
服務(wù)類代碼:在服務(wù)類的OnStart和OnStop方法,根據(jù)實(shí)際業(yè)務(wù)編寫代碼。
using System;using System.Collections.Generic;using System.IO;using System.ServiceProcess;using System.Threading;
namespace Fountain.ServiceHost.AutoWorker{    public partial class ServiceLog : ServiceBase    {        // 刪除日志計(jì)時(shí)器        private System.Threading.Timer deleteTimer;        /// <summary>        /// 構(gòu)造方法        /// </summary>        public ServiceLog()        {            InitializeComponent();        }        /// <summary>        /// 服務(wù)啟動(dòng):服務(wù)運(yùn)行時(shí)需采取的操作。        /// </summary>        /// <param name="args"></param>        protected override void OnStart(string[] args)        {            TimerCallback deleteTimerCallback = new TimerCallback(Delete);            //            this.deleteTimer = new System.Threading.Timer(deleteTimerCallback, 30, 5000, 60000);        }        /// <summary>        /// 服務(wù)停止:服務(wù)停止運(yùn)行時(shí)需采取的操作。        /// </summary>        protected override void OnStop()        {            this.deleteTimer?.Dispose();        }        /// <summary>        /// 刪除日志文件        /// </summary>        /// <param name="retentionDays">保留幾天的日志文件</param>        public void Delete(object retentionDays)        {            try            {                List<string> retentionFiles = new List<string>();                //文件數(shù)組                string[] keepfile = new string[Convert.ToInt32(retentionDays)];                for (int i = 0; i < Convert.ToInt32(retentionDays); i++)                {                    retentionFiles.Add(string.Format("{0:yyyyMMdd}", DateTime.Now.AddDays(-(i))));                }                DirectoryInfo directoryInfo= new DirectoryInfo($"{AppDomain.CurrentDomain.BaseDirectory}{Path.DirectorySeparatorChar}log");                //目錄是否存在                if (directoryInfo.Exists)                {                    foreach (FileInfo fileInfo in directoryInfo.GetFiles())                    {                        if (retentionFiles.Contains(fileInfo.Name))                        {                            continue;                        }                        fileInfo.Delete();                    }                }            }            catch            {            }        }    }}

2、部署服務(wù)應(yīng)用項(xiàng)目

右擊項(xiàng)目----》選擇添加----》類

選擇安裝程序類----》點(diǎn)擊添加。創(chuàng)建安裝程序成功,并自動(dòng)生成繼承自Installer類的類。示例將安裝類命名為【W(wǎng)inServiceInstaller】

安裝服務(wù)類代碼:服務(wù)組件中的服務(wù)名稱、服務(wù)描述等基本信息。
using System;using System.ComponentModel;using System.ServiceProcess;namespace Fountain.ServiceHost.Worker{    [RunInstaller(true)]    public partial class WinServiceInstaller : System.Configuration.Install.Installer    {        private readonly ServiceProcessInstaller serviceProcessInstaller;        private readonly ServiceInstaller serviceInstaller;        public WinServiceInstaller()        {            try            {                string windowsServiceName = "ClearLogFile";                string windowsServiceDescription = "清理日志歷史文件";                serviceProcessInstaller = new ServiceProcessInstaller                {                    //賬戶類型                    Account = ServiceAccount.LocalSystem                };                serviceInstaller = new ServiceInstaller                {                    StartType = ServiceStartMode.Automatic,                    //服務(wù)名稱                    ServiceName = windowsServiceName,                    //服務(wù)描述                    Description = windowsServiceDescription                };                base.Installers.Add(serviceProcessInstaller);                base.Installers.Add(serviceInstaller);             }            catch (Exception objException)            {                throw new Exception(objException.Message);            }        }    }}
編譯項(xiàng)目程序,部署到Windows服務(wù):使用installutil.exe。
#region 示例安裝部署// 以管理員身份運(yùn)行cmd命令,把目錄定位到InstallUtil.exe 所在的目錄// 安裝服務(wù)InstallUtil C:\Project\WinService\WebWorker.exe// 卸載服務(wù)InstallUtil /u C:\Project\WinService\WebWorker.exe#endregion 
也可編寫一個(gè)界面程序進(jìn)行安裝與卸載服務(wù)。
示例代碼:
using System;using System.Configuration.Install;using System.ServiceProcess;using System.Windows.Forms;
namespace Fountain.ServiceHost.Main{    public partial class FormMain : Form    {        /// <summary>        /// 構(gòu)造方法        /// </summary>        public FormMain()        {            InitializeComponent();        }        /// <summary>        /// 安裝服務(wù)        /// </summary>        /// <param name="sender"></param>        /// <param name="e"></param>        private void buttonInstall_Click(object sender, EventArgs e)        {            try            {                if (this.GetService(this.textBoxServiceName.Text) == null)                {                    string servicepath = AppDomain.CurrentDomain.BaseDirectory + @"AutoWorker.exe";                    ManagedInstallerClass.InstallHelper(new string[] { servicepath });                    MessageBox.Show(this.textBoxServiceName.Text + "服務(wù)已安載成功");                }            }            catch (Exception exception)            {                if (exception.InnerException != null)                {                    MessageBox.Show(exception.InnerException.Message);                }                else                {                    MessageBox.Show(exception.Message);                }            }        }        /// <summary>        /// 卸載服務(wù)        /// </summary>        /// <param name="sender"></param>        /// <param name="e"></param>        private void buttonUnInstall_Click(object sender, EventArgs e)        {            try            {                if (this.GetService(this.textBoxServiceName.Text) != null)                {                    string servicepath = AppDomain.CurrentDomain.BaseDirectory + @"AutoWorker.exe";                    ManagedInstallerClass.InstallHelper(new string[] { "/u", servicepath });                    MessageBox.Show(this.textBoxServiceName.Text +  "服務(wù)已卸載成功");                }            }            catch (Exception exception)            {                if (exception.InnerException != null)                {                    MessageBox.Show(exception.InnerException.Message);                }                else                {                    MessageBox.Show(exception.Message);                }            }        }        /// <summary>        /// 獲得服務(wù)的對(duì)象        /// </summary>        /// <param name="servicename">服務(wù)名稱</param>        /// <returns>ServiceController對(duì)象,若沒有該服務(wù),則返回null</returns>        public  ServiceController GetService(string servicename)        {            try            {                ServiceController[] serviceController = ServiceController.GetServices();                foreach (ServiceController serviceItem in serviceController)                {                    if (serviceItem.ServiceName.Equals(servicename, StringComparison.OrdinalIgnoreCase))                    {                        return serviceItem;                    }                }                return null;            }            catch (Exception exception)            {                throw new Exception(exception.Message);            }        }    }}
界面效果:

示例完整代碼:

https://github.com/fountyuan/Fountain.ServiceHost.AutoWorker

小結(jié)

以上是C#使用ServiceBase類創(chuàng)建與部署服務(wù)應(yīng)用程序的全部內(nèi)容,是.NET Framework 提供的一種實(shí)現(xiàn)方式。而NET Core 3.0 及以上和.NET 6.0還提供了另一種實(shí)現(xiàn)方式,后續(xù)介紹。希望本文對(duì)有需要的朋友能提供一些參考。如有不到之處,請(qǐng)多多包涵。


該文章在 2024/6/8 18:06:30 編輯過
關(guān)鍵字查詢
相關(guān)文章
正在查詢...
點(diǎn)晴ERP是一款針對(duì)中小制造業(yè)的專業(yè)生產(chǎn)管理軟件系統(tǒng),系統(tǒng)成熟度和易用性得到了國內(nèi)大量中小企業(yè)的青睞。
點(diǎn)晴PMS碼頭管理系統(tǒng)主要針對(duì)港口碼頭集裝箱與散貨日常運(yùn)作、調(diào)度、堆場、車隊(duì)、財(cái)務(wù)費(fèi)用、相關(guān)報(bào)表等業(yè)務(wù)管理,結(jié)合碼頭的業(yè)務(wù)特點(diǎn),圍繞調(diào)度、堆場作業(yè)而開發(fā)的。集技術(shù)的先進(jìn)性、管理的有效性于一體,是物流碼頭及其他港口類企業(yè)的高效ERP管理信息系統(tǒng)。
點(diǎn)晴WMS倉儲(chǔ)管理系統(tǒng)提供了貨物產(chǎn)品管理,銷售管理,采購管理,倉儲(chǔ)管理,倉庫管理,保質(zhì)期管理,貨位管理,庫位管理,生產(chǎn)管理,WMS管理系統(tǒng),標(biāo)簽打印,條形碼,二維碼管理,批號(hào)管理軟件。
點(diǎn)晴免費(fèi)OA是一款軟件和通用服務(wù)都免費(fèi),不限功能、不限時(shí)間、不限用戶的免費(fèi)OA協(xié)同辦公管理系統(tǒng)。
Copyright 2010-2025 ClickSun All Rights Reserved