C#--Windows服务--创建和运行(安装、启动、停止、重启、卸载)

C#-Windows服务创建和运行
Windows服务创建和运行

适用场景:
ASP.Net通常是一个无状态的提供程序,不支持持续运行代码或者定时执行某段代码,所以我们需要构建自己的Windows服务来运行那些定时任务。
项目中需要定时处理数据时可以使用服务,比如短信发送,邮件提醒,和其他信息系统集合对接等定时任务

话不多说,简单介绍如何创建

1.新建服务
从 Visual Studio“文件”菜单中,选择“新建” > “项目”(或按 Ctrl+Shift+N),打开“新建项目”窗口
导航到并选择“Windows 服务 (.NET Framework)”项目模板。

2.更改服务名称:
右击“属性”,找到“ServiceName”属性,修改成“MyService”

3.添加安装程序
(1)右击“Service.cs[设计]”窗口,选择“添加安装程序”。
可以看见项目中自动多了“serviceProcessInstall1”,"serviceInstaller1"这两个文件。

(2) 设置组件serviceProcessInstaller1的主要属性,Accout:账户类型,LocalSystem本地系统服务;

4.添加项目需要的业务代码

using System;
 using System.Collections.Generic;
 using System.Linq;
 using System.ServiceProcess;
 using System.Text;
 using System.Threading.Tasks;
 namespace WindowsService
 {
     static class Program
     {
         /// <summary>
         /// 应用程序的主入口点。
         /// </summary>
         static void Main()
         {
             ServiceBase[] ServicesToRun;
             ServicesToRun = new ServiceBase[]
             {
                 new Service1()    //注意与你建的服务名称一致
             };
             ServiceBase.Run(ServicesToRun);
         }
     }
 }

打开“Program.cs”,可以看到服务启动后,首先执行Service1。
这里,我们已5秒钟一个轮询,写一条日志信息为例。
(1)首先添加文件夹“Utils”,添加类“Common.cs”,用于记录日志
复制代码

using System;
 using System.Collections.Generic;
 using System.IO;
 using System.Linq;
 using System.Text;
 using System.Threading.Tasks;
 namespace WindowsService.Utils
 {
     public static class Common
     {
         public static void WriteLogs(string content)
         {
             string path = AppDomain.CurrentDomain.BaseDirectory;
             string LogName =  System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Namespace.Split('.')[0];
             string[] sArray = path.Split(new string[] { LogName },  StringSplitOptions.RemoveEmptyEntries);
             string aa = sArray[0] + "\\" + LogName + "Log\\";
             path = aa;
             if (!string.IsNullOrEmpty(path))
             {
                 if (!Directory.Exists(path))
                 {
                     Directory.CreateDirectory(path);
                 }
                 path = path + "\\" + DateTime.Now.ToString("yyyy-MM-dd") + ".txt";//
                 if (!File.Exists(path))
                 {
                     FileStream fs = File.Create(path);
                     fs.Close();
                 }
                 if (File.Exists(path))
                 {
                     StreamWriter sw = new StreamWriter(path, true,  System.Text.Encoding.Default);
                     sw.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "----" +  content + "\r\n");
                     sw.Close();
                 }
             }
         }
     }
 }

(2)创建业务代码类“HandleService.cs”
复制代码

 using System;
 using System.Collections.Generic;
 using System.Linq;
 using System.Text;
 using System.Threading.Tasks;
 using WindowsService.Utils;
 namespace WindowsService
 {
     public class HandleService
     {
         public static void ActionRun(ref bool isRun)
         {
             try {
                 isRun = true;
                 //业务代码:这里可以写你的业务相关的代码
                Common.WriteLogs("这是一条日志");
             }
             catch (Exception ex)
             {
                 Common.WriteLogs(ex.Message);
             }
             finally
             {
                 isRun = false;
             }
         }
     }
 }

复制代码

(3)设置Service1的定时触发功能,
需要添加定时器Timer,定时执行上一步创建的“HandleService.cs”中的业务逻辑,完整代码如下
复制代码

 using System;
 using System.Collections.Generic;
 using System.ComponentModel;
 using System.Data;
 using System.Diagnostics;
 using System.Linq;
 using System.ServiceProcess;
 using System.Text;
 using System.Threading.Tasks;
 using WindowsService.Utils;
 namespace WindowsService
 {
     public partial class Service1 : ServiceBase
     {
         public Service1()
         {
             InitializeComponent();
         }
         System.Timers.Timer _timer = new System.Timers.Timer();
         private bool isRun = false;
         protected override void OnStart(string[] args)
         {
             try
             {
                 //设置计时器事件间隔执行时间,以毫秒为单位,这里设置5秒执行一次
                 int _interval = 5 * 1000;    
                 _timer.Interval = _interval;     
                 _timer.AutoReset = true;  //是否自动启动
                 _timer.Enabled = true;    //是否开启计时器
                 //到达时间时,执行的事件
                 _timer.Elapsed += new System.Timers.ElapsedEventHandler(ActionRun);
                 Common.WriteLogs("服务已启动");
             }
             catch (Exception ex)
             {
                 Common.WriteLogs(ex.Message);
             }
         }
         private void ActionRun(object sender, System.Timers.ElapsedEventArgs e)
         {
             try
             {
                 //是否开启计时器
                 if (!isRun)
                 {
                     HandleService.ActionRun(ref isRun);
                 }
             }
             catch (Exception ex)
             {
                 Common.WriteLogs("Error:" + ex.Message);
             }
         }
         protected override void OnStop()
         {
             _timer.AutoReset = false;
             _timer.Enabled = false;
             _timer.Stop();
             Common.WriteLogs("服务已停止");
         }
     }
 }
  

复制代码

生成项目文件,全部生成成功后,就要开始服务的安装和启动
5.服务的安装和启动
项目成功后,在bin文件夹下找到生成的exe文件和exe.config文件,前者是运行程序,后者是服务的配置信息,实际项目中可以通过更改config中的内容,修改服务的配置信息。
安装和卸载主要使用的是.NET提供的InstallUtil.exe这个文件 ,文件位于C盘对应的目录下 C:\Windows\Microsoft.NET\Framework64\v4.0.30319,拷贝至和exe同一个目录bin下。

新建bat文件,用于安装,启动,卸载,停止,重启服务

安装.bat:

MyWinService:给你的服务起一个别名
WindowsService.exe:是你的服务项目生成的文件,
“%~dp0”:这部分是固定不变的,例如 “%~dp0你的服务项目名称.exe”,本文的服务项目名称是 WindowsService

 sc create MyWinService binPath= "%~dp0WindowsService.exe" start= auto
 net start MyWinService
 pause

启动.bat

 net start MyWinService
 pause

停止.bat

 net stop MyWinService
 pause

重启.bat

 net stop MyWinService
 net start MyWinService
 pause

卸载.bat

MyWinService:给你的服务起一个别名
WindowsService.exe:是你的服务项目生成的文件,
“%~dp0JD”:这部分是固定不变的,例如 “%~dp0JD你的服务项目名称.exe”,本文的服务项目名称是 WindowsService

 net stop MyWinService
 sc delete MyWinService binPath= "%~dp0JDWindowsService.exe" start= auto
 pause

6.运行安装文件和启动服务
双击“安装.bat”,弹出cmd窗口,如下图,表示安装成功:

双击“启动.bat”,如下图表示成功启动服务

7.查看业务代码的日志写入是否成功
找到项目文件同一个目录下的Log文件,找到日志,如下图所示:

可以看到日志文件每隔5秒会写入一条日志文件,至此整个服务运行成功。

本文源码下载:
链接:https://pan.baidu.com/s/1gsJ7m12NP7puxXNb4IPVEA
提取码:a62m

原文链接 https://www.cnblogs.com/ywkcode/p/11569593.html

猜你喜欢

转载自blog.csdn.net/VIP_CR/article/details/104840084