当前位置: 首页 > news >正文

Windows 服务

 Windiws服务 允许用户创建可在其自身的Windows会话中长时间运行的可执行应用程序。这些服务可在计算机启动时自动重启,也可以暂停和停止,并且不显示任何用户界面面。这些功能是服务非常在计算机上使用,或者需要长时间运行的功能的情况。

一、编程方式创建服务

1、以编程方式创建服务,必须执行的步骤:

  • 必须将服务类设置为从 ServiceBase 继承需引入命名空间System.ServiceProcess.dll。
  • 必须为服务项目创建Main方法,该方法定义要运行的服务,并在其上调用 Run 方法。
  • 必须替代 OnStart 和 OnStop 过程,并填入希望运行的代码。
  • 添加服务应用程序,所必需的安装程序。
  • 生产解决方案。
  • 安装服务。

ServiceBase 类的 Run 方法。 这是服务的主入口点。 

使用 Windows 服务模板创建服务时,将在应用程序的 Main 方法中插入代码以运行该服务。 此代码如下所示:

System.ServiceProcess.ServiceBase[] ServicesToRun;

ServicesToRun = new System.ServiceProcess.ServiceBase[]

  { new Service1() };

System.ServiceProcess.ServiceBase.Run(ServicesToRun);

 

服务创建实例:

1、新建一个 Windows 服务,并命名为"MyWindowsService"。

2、在解决方案内,将Service1.cs改为Myservice.cs。

 

3、在代码编辑器内替换以下代码,如下图所示:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.Threading.Tasks;namespace MyWindowsService
{public partial class MyService : ServiceBase{public MyService(){InitializeComponent();}string filePath = @"D:\MyServiceLog.txt";protected override void OnStart(string[] args){using (FileStream fs = new FileStream(filePath, FileMode.OpenOrCreate, FileAccess.Write)){using (StreamWriter sw = new StreamWriter(fs)){sw.WriteLine("{0},服务启动!",DateTime.Now);}}}protected override void OnStop(){using (FileStream fs = new FileStream(filePath, FileMode.OpenOrCreate, FileAccess.Write)){using (StreamWriter sw = new StreamWriter(fs)){sw.WriteLine("{0},服务停止!", DateTime.Now);}}}}
}

4、点击项目“MyWindowsService”进入“MyService”设计界面,右键空白处,选中“添加安装程序”,如下图所示:

5、此时会生成两个组件,分别为“serviceInstaller1”及“serviceProcessInstaller1”,如下图所示:

6、点击“serviceInstaller1”,在“属性”窗体中将ServiceName改为"MyService",DisplayName改为"MyService我的服务", Description改为"我的服务描述", StartType保持为"Manual"。

Manual

该服务必须在安装后手动启动

Automatic

只要重启计算机,服务就将自行启动。

Disabled

服务无法启动。

如下图所示:

 

7、点击“serviceProcessInstaller1”,在“属性”窗体将Account改为"LocalSystem",如下图所示:

默认情况下,服务在与登录用户不同的安全性上下文中运行。 服务在名为 LocalSystem 的默认系统帐户的上下文中运行,这样使服务拥有与用户不同的针对系统资源的访问权限。 可以更改此行为以指定应在其下运行服务的其他用户帐户。

可以通过操作服务运行于其中的进程的 Account 属性来设置安全性上下文。 此属性允许将服务设置为以下四种帐户类型之一:

User,该帐户会导致系统在安装服务时提示输入有效的用户名和密码,并在网络上单个用户指定的帐户的上下文中运行;

LocalService,该帐户在用作本地计算机上的非特权用户的帐户的上下文中运行,并向任意远程服务器提供匿名凭据;

LocalSystem,该帐户在提供广泛本地权限的帐户的上下文中运行,并向任意远程服务器提供计算机凭据;

NetworkService,该帐户在用作本地计算机上的非特权用户的帐户的上下文中运行,并向任意远程服务器提供计算机凭据。

 

8、右键项目“MyWindowsService”,选择并点击“生成”/“重新生成”,如下图所示:

 

9、恭喜,Windows服务已经创建完毕。

二、创建Windows窗体:安装、启动、停止、卸载服务

 1、在同一个解决方案里,新建一个Windows Form项目,并命名为WindowsServiceClient。如下图所示:

2、将此项目设定为"项目启动项"。在窗体内添加四个按钮,分别为安装服务、启动服务、停止服务、卸载服务,并添加服务状态文本框。如下图所示:

 

3、按下"F7"进入代码编辑界面,引用“System.ServiceProcess”及“System.Configuration.Install”,并填写如下代码:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Configuration.Install;
using System.ServiceProcess;
using System.Collections;namespace WindowsServiceClient
{public partial class Form1 : Form{public Form1(){InitializeComponent();}string serviceFilePath = $"{Application.StartupPath}\\MyWindowsService.exe";string serviceName = "MyService";//判定服务是否存在private bool IsServiceExisted(string serviceName){//检索本地计算机上的所有服务ServiceController[] services = ServiceController.GetServices();foreach (ServiceController item in services){if (item.ServiceName.ToUpper() == serviceName.ToUpper()){return true;}}return false;}//安装服务private void InstallService(string serviceFilePath){// 加载程序集,并在其中运行的所有安装程序using (AssemblyInstaller installer = new AssemblyInstaller()){//获取或设置一个值,该值指示是否创建一个新 System.Configuration.Install.InstallContext 对象的程序集的安装。installer.UseNewContext = true;installer.Path = serviceFilePath;IDictionary savedState = new Hashtable();//执行安装
                installer.Install(savedState);//完成安装事务
                installer.Commit(savedState);}}//卸载安装private void UninstallService(string serviceFilePath){using (AssemblyInstaller installer = new AssemblyInstaller()){installer.UseNewContext = true;installer.Path = serviceFilePath;installer.Uninstall(null);}}//启动服务private void ServiceStart(string serviceName){using (ServiceController control = new ServiceController(serviceName)){if (control.Status == ServiceControllerStatus.Stopped){control.Start();control.WaitForStatus(ServiceControllerStatus.Running);}}}//停止服务private void ServiceStop(string serviceName){using (ServiceController control = new ServiceController(serviceName)){if (control.Status == ServiceControllerStatus.Running){control.Stop();control.WaitForStatus(ServiceControllerStatus.Stopped);}}}//事件:安装服务private void btn_az_Click(object sender, EventArgs e){if (this.IsServiceExisted(serviceName)){this.UninstallService(serviceName);}this.InstallService(serviceFilePath);txt.Text = "服务安装成功";}//事件:启动服务private void btn_run_Click(object sender, EventArgs e){if (this.IsServiceExisted(serviceName)){this.ServiceStart(serviceName);txt.Text = "服务正在运行";}}//事件:停止服务private void btn_stop_Click(object sender, EventArgs e){if (this.IsServiceExisted(serviceName)){this.ServiceStop(serviceName);txt.Text = "服务停止";}}//事件:卸载服务private void btn_xiezai_Click(object sender, EventArgs e){if (this.IsServiceExisted(serviceName)){this.ServiceStop(serviceName);this.UninstallService(serviceFilePath);txt.Text = "服务已卸载";}}}
}

4、为了后续调试服务及安装卸载服务的需要,将已生成的MyWindowsService.exe引用到本Windows Form窗体,如下图所示:

5、由于需要安装服务,故需要使用UAC中Administrator的权限,鼠标右击项目“WindowsServiceClient”,在弹出的上下文菜单中选择“添加”->“新建项”,在弹出的选择窗体中选择“应用程序清单文件”并单击确定,如下图所示:

6、打开该文件,并将<requestedExecutionLevel level="asInvoker" uiAccess="false" />改为<requestedExecutionLevel  level="requireAdministrator" uiAccess="false" />,如下图所示:

7、IDE启动后,将会弹出如下所示的窗体(有的系统因UAC配置有可能不显示),需要用管理员权限打开:

8、重新打开后,在IDE运行WindowsServiceClient项目;

9、使用WIN+R的方式打开运行窗体,并在窗体内输入services.msc后打开服务,如下图所示:

10.在窗体中,进行“安装服务”等操作。

11.以上启动及停止服务将会写入D:\MyServiceLog.txt,内容如下所示:

 

源代码下载:

 

三、如何调试服务

要调试服务,其实很简单,如需将服务附加进程到需要调试的项目里面即可,假如要调试刚才建的服务,现在OnStop事件里设置断点,如下所示:

2、启动“WindowsServiceClient”项目,在“调试”菜单中选择“附件到进程”(服务必须事先安装),如下所示:

、找到“MyWindowsService.exe”,点击“附加”按钮,如下图所示:

 

4、点击“停止服务”按钮,程序将会在设置断点的地方中断,如下图所示:

 

 此文章参考:https://www.cnblogs.com/cncc/p/7170951.html  完成。

转载于:https://www.cnblogs.com/AndyChen2015/p/9553295.html


http://www.taodudu.cc/news/show-4974475.html

相关文章:

  • js 解析json数据实现快递包裹的查询
  • 12、 一键查快递
  • 已知顺丰快递既可以发陆运,也可以发空运;EMS只能发空运,圆通只能发陆运。 小明现在发送快递,为其设计两个方法,分别用来发空运和陆运。
  • valgrind 工具使用
  • valgrind 工具介绍和简单的使用
  • valgrind 简介(内存检查工具)
  • 工具:valgrind学习
  • Win10下CS231n assignment1 环境配置
  • cs231n assignment2 PyTorch
  • Stanford cs231n'18 课程及作业详细解读
  • CS231n第一节
  • cs231n笔记总结
  • 【实验小结】cs231n assignment1 knn 部分
  • CS231n 两层神经网络反向传播实现
  • 【深度学习】cs231n计算机视觉 CNN(卷积神经网络)
  • FreeCAD错误:没有激活的实体 解决办法
  • springboot 整合mysql clickhouse 多数据源
  • 自定义数据源 整合 Mybatis-Plus-多租户
  • 2020FME博客大赛——FME在数据整合中的应用
  • 从零开始Tableau | 2.数据整合
  • 代码分析 | 单细胞转录组数据整合详解
  • 怎样的数据报表才能将公司全部业务数据整合在一起
  • 数据仓库、数据整合、ETL、ELT和EII之间的区别?
  • 生物信息学|MOLI:基于深度神经网络进行多组学数据整合并用于药物反应预测
  • 数据清洗 Chapter04 | 数据整合
  • 分享一篇 Science 里不同批次的单细胞数据整合及批次校正方法
  • 数据库数据整合
  • 数据挖掘二:数据整合
  • 数据整合基础知识介绍
  • 从零开始设计键值数据库(KEY-VALUE STORE)