C#Windows服务程序编写浅析

开发 后端
C#Windows服务程序编写向你介绍了基本的C#Windows服务程序编写步骤,希望对你了解C#Windows服务程序编写有所帮助。

C#Windows服务程序编写是如何实现的呢?

C#Windows服务程序编写是一种比较高级的编程技术,内部使用了很多Windows操作系统的核心功能,但微软.NET框架已经很好的封装了这些技术细节,使得我们可以很方便的使用C#编写自己的Windows服务,其基本过程一般为

Windows服务程序编写1.创建C#工程。

创建一个EXE工程,可以是WinForm或者命令行格式的。添加对System.ServiceProcess.dll和System.Configuration.Install.dll的引用。

Windows服务程序编写2.创建服务类。

新增一个类,该类型继承System.ServiceProcess.ServiceBase类型,在构造函数中设置ServiceName属性来指明该服务的名称。然后重载它的OnStart方法来响应启动服务的事件,重载OnStop方法来响应停止服务的事件,重载OnPause方法来响应暂停服务的事件,重载OnContinue方法来响应恢复提供服务的事件。在重载这些方法时必须要立即返回,其中不能出现长时间的操作,若处理时间过长则Windows服务管理器会觉得该Windows服务停止响应而报错。为此我们可以使用一个线程来进行实际的工作,而OnStart方法创建线程,OnStop方法关闭线程,OnPause方法挂起线程,而OnContinue方法来恢复运行线程。

Windows服务程序编写3.启动服务。

在main函数中调用“System.ServiceProcess.ServiceBase.Run( 自定义服务类的实例 )”来运行服务。比如“System.ServiceProcess.ServiceBase.Run( new MyService() )”,这里的MyService就是继承自ServiceBase。

Windows服务程序编写4.安装服务。

新增一个类,该类型继承自System.Configuration.Install.Installer类型,该类型用于配合微软.NET框架自带的安装命令行工具InstallUtil.exe的。我们为该类型附加System.ComponentModel.RunInstallerAttribute特性,并在它的构造函数中使用System.ServiceProcess.ServiceInstaller对象和System.ServiceProcess.ServiceProcessInstaller对象向系统提供该服务的安装信息。程序编译后我们可以使用命令行“InstallUtil.exe   EXE文件名”向Windows服务管理器注册服务,可以使用命令行“InstallUtil.exe /u EXE文件名”从Windows服务管理器中注销服务。

Windows服务程序编写5.编写服务客户端。

这是一个根据实际情况而可选的过程,由于Windows服务是没有用户界面的,因此我们可以编写一个具有用户界面的程序来显示和控制Windows服务提供的数据,并进行一些系统设置等操作。比如对于MS SQL Server,数据库引擎是以服务的形式存在,而SQL Server企业管理器就是一个客户端软件。

C#Windows服务程序编写的基本步骤就向你介绍到这里,希望对你了解和学习C#Windows服务程序编写有所帮助。

【编辑推荐】

  1. C#Windows服务程序之添加安装程序图解
  2. C#Windows服务程序开发实例浅析
  3. C#Windows服务程序开发浅析
  4. C#Windows服务程序的快速开发
  5. C#WINDOWS服务交互的实现
责任编辑:仲衡 来源: 51CTO.com
相关推荐

2009-08-14 14:25:09

Windows服务程序

2009-08-14 15:47:18

C#Windows服务

2009-08-14 14:17:16

C#Windows服务

2009-08-14 15:19:38

Windows服务程序Windows服务

2009-08-14 16:13:25

C#windows服务

2009-08-14 16:24:00

Windows服务程序

2009-08-14 14:45:03

C#Windows服务

2009-08-14 16:48:39

C#Windows服务

2009-08-14 15:54:50

Windows服务程序C#Windows服务

2009-08-14 10:50:09

Windows服务介绍

2009-08-14 13:41:13

C#Windows服务

2009-08-14 14:53:55

WINDOWS服务交互

2009-08-14 11:15:19

文件监视C#Windows服务

2009-08-14 11:00:16

C#创建Windows

2011-05-17 14:53:35

C

2009-08-14 18:04:59

C#Windows应用

2009-08-14 17:27:30

C#Windows应用

2009-08-14 17:36:20

C#Windows应用

2009-08-14 16:41:22

C#启动Windows

2009-08-14 10:42:16

Timer控件的使用C#windows服务
点赞
收藏

51CTO技术栈公众号