公交车上荫蒂添的好舒服的电影-公用玩物(np双xing总受)-公用小荡货芊芊-公与妇仑乱hd-攻把受做哭边走边肉楼梯play-古装一级淫片a免费播放口

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

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


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

前言

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

ServiceBase類

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

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

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

配置新項目的項目名稱、存儲目錄和選擇使用的目標框架。示例使用【Fountain.ServiceHost.Worker】為項目名稱和解決方案名稱。

項目創(chuàng)建成功后,我們會看到創(chuàng)建了Service1和Program二個類??梢愿鶕?jù)實際需要對Service1類進行重命名。
程序入口代碼:
using System.ServiceProcess;namespace Fountain.ServiceHost.AutoWorker{    internal static class Program    {        /// <summary>        /// 應(yīng)用程序的主入口點。        /// </summary>        static void Main()        {            ServiceBase[] ServicesToRun;            ServicesToRun = new ServiceBase[]            {                new ServiceLog()            };            ServiceBase.Run(ServicesToRun);        }    }}
服務(wù)類代碼:在服務(wù)類的OnStart和OnStop方法,根據(jù)實際業(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    {        // 刪除日志計時器        private System.Threading.Timer deleteTimer;        /// <summary>        /// 構(gòu)造方法        /// </summary>        public ServiceLog()        {            InitializeComponent();        }        /// <summary>        /// 服務(wù)啟動:服務(wù)運行時需采取的操作。        /// </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ù)停止運行時需采取的操作。        /// </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)用項目

右擊項目----》選擇添加----》類

選擇安裝程序類----》點擊添加。創(chuà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);            }        }    }}
編譯項目程序,部署到Windows服務(wù):使用installutil.exe。
#region 示例安裝部署// 以管理員身份運行cmd命令,把目錄定位到InstallUtil.exe 所在的目錄// 安裝服務(wù)InstallUtil C:\Project\WinService\WebWorker.exe// 卸載服務(wù)InstallUtil /u C:\Project\WinService\WebWorker.exe#endregion 
也可編寫一個界面程序進行安裝與卸載服務(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ù)的對象        /// </summary>        /// <param name="servicename">服務(wù)名稱</param>        /// <returns>ServiceController對象,若沒有該服務(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 提供的一種實現(xiàn)方式。而NET Core 3.0 及以上和.NET 6.0還提供了另一種實現(xiàn)方式,后續(xù)介紹。希望本文對有需要的朋友能提供一些參考。如有不到之處,請多多包涵。


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

主站蜘蛛池模板: 成人无码精品一区二区三区 | 国产精品成人a在线观看网站。 | 白丝乳交内射 | 91婷婷韩国欧美一 | 国产精品日日做人人爱 | 韩国欧美日本亚洲一区二 | 国产性爱毛片亚洲性爱在线 | 国产女学生破女初在线观看 | 国产自偷在线拍精品热 | 国产白丝jk被疯狂输出免费 | 精品久久久久久无码人妻热 | 国产无码毛片一区二区三区 | 91精品人妻一区二区三区浪潮 | 国产美女极度色诱视频 | 国产精品乱码一二三区的特点 | 69成品人视频免费看手机最新 | 国产免费一区二区三区在线看 | 成人午夜精品网站在线观看 | 国产专区亚洲欧美另类在线91 | 91热久久免费频精品 | 国产三级精品三级男人的天堂 | 国产99久久九九精品无码 | 国产午夜一级毛片 | 国产成人免费无码av在线播放 | 国产一区二区三区无码观看 | 精品91自产拍在线观看55 | 国产成人性生交大片免费看 | 国产精品无码免费专区 | 国产亚洲欧美观看在线一区 | 国产一级无码免费视频 | 91探花国产综合在线精 | 国产精品国产对白熟妇 | 911无码在线精 | 国产精品视频人人做人人爽 | 国产成人综合亚洲av | 69国产精品视频免费 | 国产精品人妻一 | 国产剧情av不卡在线观看 | 国产高清在线国产 | 精品五月天六月花一区二区 | 精品日韩一区二区三区 |