`
wsql
  • 浏览: 11777310 次
  • 性别: Icon_minigender_1
  • 来自: 深圳
文章分类
社区版块
存档分类
最新评论

如何创建、安装和调试Windows服务

 
阅读更多

我们将研究如何创建一个作为Windows服务的应用程序。内容包含什么是Windows服务,如何创建、安装和调试它们。会用到System.ServiceProcess.ServiceBase命名空间的类。

什么是Windows服务?

Windows服务应用程序是一种需要长期运行的应用程序,它对于服务器环境特别适合。它没有用户界面,并且也不会产生任何可视输出。任何用户消息都会被写进Windows事件日志。计算机启动时,服务会自动开始运行。它们不要用户一定登录才运行,它们能在包括这个系统内的任何用户环境下运行。通过服务控制管理器,Windows服务是可控的,可以终止、暂停及当需要时启动。
Windows 服务,以前的NT服务,都是被作为Windows NT操作系统的一部分引进来的。它们在Windows 9x及Windows Me下没有。你需要使用NT级别的操作系统来运行Windows服务,诸如:Windows NT、Windows 2000 Professional或Windows 2000 Server。举例而言,以Windows服务形式的产品有:Microsoft Exchange、SQL Server,还有别的如设置计算机时钟的Windows Time服务。

创建一个Windows服务
我们即将创建的这个服务除了演示什么也不做。服务被启动时会把一个条目信息登记到一个数据库当中来指明这个服务已经启动了。在服务运行期间,它会在指定的时间间隔内定期创建一个数据库项目记录。服务停止时会创建最后一条数据库记录。这个服务会自动向Windows应用程序日志当中登记下它成功启动或停止时的记录。
Visual Studio .NET能够使创建一个Windows服务变成相当简单的一件事情。启动我们的演示服务程序的说明概述如下。
1. 新建一个项目
2. 从一个可用的项目模板列表当中选择Windows服务
3. 设计器会以设计模式打开
4. 从工具箱的组件表当中拖动一个Timer对象到这个设计表面上 (注意: 要确保是从组件列表而不是从Windows窗体列表当中使用Timer)
5. 设置Timer属性,Enabled属性为False,Interval属性30000毫秒
6. 切换到代码视图页(按F7或在视图菜单当中选择代码),然后为这个服务填加功能

Windows服务的构成
在你类后面所包含的代码里,你会注意到你所创建的Windows服务扩充了System.ServiceProcess.Service类。所有以.NET方式建立的Windows服务必须扩充这个类。它会要求你的服务重载下面的方法,Visual Studio默认时包括了这些方法。
• Dispose – 清除任何受控和不受控资源(managed and unmanaged resources)
• OnStart – 控制服务启动
• OnStop – 控制服务停止
数据库表脚本样例
在这个例子中使用的数据库表是使用下面的T-SQL脚本创建的。我选择SQL Server数据库。你可以很容易修改这个例子让它在Access或任何你所选择的别的数据库下运行。
CREATE TABLE [dbo].[MyServiceLog] (
[in_LogId] [int] IDENTITY (1, 1) NOT NULL,
[vc_Status] [nvarchar] (40)
COLLATE SQL_Latin1_General_CP1_CI_AS NOT NULL,
[dt_Created] [datetime] NOT NULL
) ON [PRIMARY]

Windows服务样例
下面就是我命名为MyService的Windows服务的所有源代码。大多数源代码是由Visual Studio自动生成的。

Code
usingSystem;
usingSystem.Collections;
usingSystem.ComponentModel;
usingSystem.Data;
usingSystem.Data.SqlClient;
usingSystem.Diagnostics;
usingSystem.ServiceProcess;
namespaceCodeGuru.MyWindowsService
{
publicclassMyService:System.ServiceProcess.ServiceBase
{
privateSystem.Timers.Timertimer1;
///<remarks>
///Requireddesignervariable.
///</remarks>
privateSystem.ComponentModel.Containercomponents=null;
publicMyService()
{
//ThiscallisrequiredbytheWindows.Forms
//ComponentDesigner.
InitializeComponent();
}
//Themainentrypointfortheprocess
staticvoidMain()
{
System.ServiceProcess.ServiceBase[]ServicesToRun;

ServicesToRun=newSystem.ServiceProcess.ServiceBase[]
{newMyService()};
System.ServiceProcess.ServiceBase.Run(ServicesToRun);
}
///<summary>
///RequiredmethodforDesignersupport-donotmodify
///thecontentsofthismethodwiththecodeeditor.
///</summary>
privatevoidInitializeComponent()
{
this.timer1=newSystem.Timers.Timer();
((System.ComponentModel.ISupportInitialize)
(this.timer1)).BeginInit();
//
//timer1
//
this.timer1.Interval=30000;
this.timer1.Elapsed+=
newSystem.Timers.ElapsedEventHandler(this.timer1_Elapsed);
//
//MyService
//
this.ServiceName="MySampleService";
((System.ComponentModel.ISupportInitialize)
(this.timer1)).EndInit();
}
///<summary>
///Cleanupanyresourcesbeingused.
///</summary>
protectedoverridevoidDispose(booldisposing)
{
if(disposing)
{
if(components!=null)
{
components.Dispose();
}
}
base.Dispose(disposing);
}
///<summary>
///Setthingsinmotionsoyourservicecandoitswork.
///</summary>
protectedoverridevoidOnStart(string[]args)
{
this.timer1.Enabled=true;
this.LogMessage("ServiceStarted");
}

///<summary>
///Stopthisservice.
///</summary>
protectedoverridevoidOnStop()
{
this.timer1.Enabled=false;
this.LogMessage("ServiceStopped");
}
/*
*RespondtotheElapsedeventofthetimercontrol
*/
privatevoidtimer1_Elapsed(objectsender,
System.Timers.ElapsedEventArgse)
{
this.LogMessage("ServiceRunning");
}
/*
*Logspecifiedmessagetodatabase
*/
privatevoidLogMessage(stringMessage)
{
SqlConnectionconnection=null;
SqlCommandcommand=null;
try
{
connection=newSqlConnection(
"Server=localhost;Database=SampleDatabase;Integrated
Security=false;UserId=sa;Password=;");
command=newSqlCommand(
"INSERTINTOMyServiceLog(vc_Status,dt_Created)
VALUES(’"+Message+"’,getdate())",connection);
connection.Open();
intnumrows=command.ExecuteNonQuery();
}
catch(Exceptionex)
{
System.Diagnostics.Debug.WriteLine(ex.Message);
}
finally
{
command.Dispose();
connection.Dispose();
}
}
}
}


安装Windows服务
Windows服务不同于普通Windows应用程序。不可能简简单单地通过运行一个EXE就启动Windows服务了。安装一个Windows服务应该通过使用.NET Framework提供的InstallUtil.exe来完成,或者通过诸如一个Microsoft Installer (MSI)这样的文件部署项目完成。

添加服务安装程序
创建一个Windows服务,仅用InstallUtil程序去安装这个服务是不够的。你必须还要把一个服务安装程序添加到你的Windows服务当中,这样便于InstallUtil或是任何别的安装程序知道应用你服务的是怎样的配置设置。
1. 将这个服务程序切换到设计视图
2. 右击设计视图选择“添加安装程序”
3. 切换到刚被添加的ProjectInstaller的设计视图
4. 设置serviceInstaller1组件的属性:
1) ServiceName = My Sample Service
2) StartType = Automatic
5. 设置serviceProcessInstaller1组件的属性
1) Account = LocalSystem
6. 生成解决方案
在完成上面的几个步骤之后,会自动由Visual Studio产生下面的源代码,它包含于ProjectInstaller.cs这个源文件内。

Code
usingSystem;
usingSystem.Collections;
usingSystem.ComponentModel;
usingSystem.Configuration.Install;
namespaceCodeGuru.MyWindowsService
{
///<summary>
///SummarydescriptionforProjectInstaller.
///</summary>
[RunInstaller(true)]
publicclassProjectInstaller:
System.Configuration.Install.Installer
{
privateSystem.ServiceProcess.ServiceProcessInstaller
serviceProcessInstaller1;
privateSystem.ServiceProcess.ServiceInstallerserviceInstaller1;
///<summary>
///Requireddesignervariable.
///</summary>
privateSystem.ComponentModel.Containercomponents=null;
publicProjectInstaller()
{
//ThiscallisrequiredbytheDesigner.
InitializeComponent();
//TODO:AddanyinitializationaftertheInitComponentcall
}
#regionComponentDesignergeneratedcode
///<summary>
///RequiredmethodforDesignersupport-donotmodify
///thecontentsofthismethodwiththecodeeditor.
///</summary>
privatevoidInitializeComponent()
{
this.serviceProcessInstaller1=new
System.ServiceProcess.ServiceProcessInstaller();
this.serviceInstaller1=new
System.ServiceProcess.ServiceInstaller();
//
//serviceProcessInstaller1
//
this.serviceProcessInstaller1.Account=
System.ServiceProcess.ServiceAccount.LocalSystem;
this.serviceProcessInstaller1.Password=null;
this.serviceProcessInstaller1.Username=null;
//
//serviceInstaller1
//
this.serviceInstaller1.ServiceName="MySampleService";
this.serviceInstaller1.StartType=
System.ServiceProcess.ServiceStartMode.Automatic;
//
//ProjectInstaller
//
this.Installers.AddRange(new
System.Configuration.Install.Installer[]
{this.serviceProcessInstaller1,this.serviceInstaller1});
}
#endregion
}
}


用InstallUtil安装Windows服务
现在这个服务已经生成,你需要把它安装好才能使用。下面操作会指导你安装你的新服务。
1. 打开Visual Studio .NET命令提示
2. 改变路径到你项目所在的bin\Debug文件夹位置(如果你以Release模式编译则在bin\Release文件夹)
3. 执行命令“InstallUtil.exe MyWindowsService.exe”注册这个服务,使它建立一个合适的注册项。
4. 右击桌面上“我的电脑”,选择“管理”就可以打计算机管理控制台
5. 在“服务和应用程序”里面的“服务”部分里,你可以发现你的Windows服务已经包含在服务列表当中了
6. 右击你的服务选择启动就可以启动你的服务了
在每次需要修改Windows服务时,这就会要求你卸载和重新安装这个服务。不过要注意在卸载这个服务前,最好确保服务管理控制台已经关闭,这会是一个很好的习惯。如果没有这样操作的话,你可能在卸载和重安装Windows服务时会遇到麻烦。仅卸载服务的话,可以执行相的InstallUtil命令用于注销服务,不过要在后面加一个/u命令开关。

调试Windows服务
从另外的角度度看,调试Windows服务绝不同于一个普通的应用程序。调试Windows服务要求的步骤更多。服务不能象你对普通应用程序做的那样,只要简单地在开发环境下执行就可以调试了。服务必须首先被安装和启动,这一点在前面部分我们已经做到了。为了便于跟踪调试代码,一旦服务被启动,你就要用Visual Studio把运行的进程附加进来(attach)。记住,对你的Windows服务做的任何修改都要对这个服务进行卸载和重安装。

附加正在运行的Windows服务
为了调试程序,有些附加Windows服务的操作说明。这些操作假定你已经安装了这个Windows服务并且它正在运行。
1. 用Visual Studio装载这个项目
2. 点击“调试”菜单
3. 点击“进程”菜单
4. 确保 显示系统进程 被选
5. 在 可用进程 列表中,把进程定位于你的可执行文件名称上点击选中它
6. 点击 附加 按钮
7. 点击 确定
8. 点击 关闭
9. 在timer1_Elapsed方法里设置一个断点,然后等它执行

总结
现在你应该对Windows服务是什么,以及如何创建、安装和调试它们有一个粗略的认识了。Windows服务的额处的功能你可以自行研究。这些功能包括暂停(OnPause)和恢复(OnContinue)的能力。暂停和恢复的能力在默认情况下没有被启用,要通过Windows服务属性来设置。

分享到:
评论

相关推荐

    C# VS 2010 创建、安装、调试 windows服务(windows service)

    C# VS 2010 创建、安装、调试 windows服务(windows service) 代码

    C# 创建windows服务源码

    C# 创建windows服务首先要安装windows服务利用InstallUtil.exe安装 源代码

    VS2013创建Windows服务与调试服务的图文方法

    1、创建Windows服务   说明: a)Description 服务描述,直接显示到Windows服务列表中的描述; b)DisplayName 服务显示名称,直接显示到Windows服务列表中的名称; c)ServiceName 服务进程名称,安装与卸载服务时...

    C# windows service 服务创建,调试,安装 方法集合 还有代码例子

    C# windows service 服务创建,调试,安装 方法集合 还有代码例子

    Windows服务程序开发实例.pdf

    Windows 服务以前被称作 NT 务,是一些运行在 Windows NT、Windows 2000 和 Windows XP 等操作系统 ...一步创建一个文件监视的 Windows 服务程序,然后介绍如何安装、测试和调试该 Windows 务程序。

    安装windows服务详细文档

    本文就向大家介绍如何运用Visual C#来一步一步创建一个文件监视的Windows服务程序,然后介绍如何安装、测试和调试该Windows服务程序。

    C#实现Windows服务

    我们将研究如何创建一个作为Windows服务的应用程序。内容包含什么是Windows服务,如何创建、安装和调试它们。

    如何用.NET创建Windows服务

    如何用.NET创建Windows服务 我们将研究如何创建一个作为Windows服务的应用程序。内容包含什么是Windows服务,如何创建、安装和调试它们。会用到System.ServiceProcess.ServiceBase命名空间的类。

    精通WindowsAPI 函数 接口 编程实例

    15.2.3 CopyFiles和AddReg等安装过程 468 15.2.4 源路径和目的路径 469 15.2.5 字符串表 469 15.3 安装程序setup.exe的编号 469 15.4 使用msi文件进行安装 472 15.4.1 Windows Installer Service 472 ...

    C#使用Windows Service的简单教程(创建、安装、卸载、调试)

    前言:Microsoft Windows 服务能够创建在它们...本文就向大家介绍如何运用C#来创建、安装、卸载、调试Windows Service程序。 一、创建Windows服务 1)用VS新建Windows 服务项目 2)默认生成文件包括Program.cs,Servic

    应用服务器的搭建-创建DNS、DHCP、FTP、Web服务器.doc

    应用服务器的搭建 创建DNS、DHCP、FTP、Web服务器 一、实验目的: 1、了解Windows 2000 Advanced Server的网络组件,并进行安装和调试。 2、了解和认识DNS服务,并简单设置DNS服务。 3、了解和认识DHCP服务,并简单...

    windowsnt 技术内幕

    回顾微软Windows NT域 回顾Windows NT域委托关系 回顾Windows NT目录服务 创建一个高效的Windows NT目录服务结构 决定所需的域控制器的数量 理解在地理上怎样安排域控制器 理解域控制器的大小和速度 计算所需的主域...

    C#编写Windows服务浅谈

    在以前,编写Windows服务程序需要程序员很强的C或C++功底。...本文就向大家介绍如何运用Visual C#来一步一步创建一个文件监视的Windows服务程序,然后介绍如何安装、测试和调试该Windows服务程序。

    Windows服务开发基本步骤和注意事项.zip_Windows编程_sillyqbl

    Windows服务开发基本步骤,包括创建,使用脚本安装和调试。一些注意点,包括控制台转服务,多服务运行方式等。

    精通Windows.API-函数、接口、编程实例.pdf

    15.2.3 CopyFiles和AddReg等安装过程 468 15.2.4 源路径和目的路径 469 15.2.5 字符串表 469 15.3 安装程序setup.exe的编号 469 15.4 使用msi文件进行安装 472 15.4.1 Windows Installer Service 472 ...

    windows驱动开发技术详解-part2

     3.6.1 SCM组件和Windows服务  3.6.2 加载NT驱动的代码  3.6.3 卸载NT驱动的代码  3.6.4 实验  3.7 WDM式驱动的加载  3.7.1 WDM的手动安装  3.7.2 简单的INF文件剖析  3.8 WDM设备安装在注册表中的...

    EasyService:在短短几分钟内将您的控制台应用程序转换为 Windows 服务

    将任何控制台应用程序转换为自安装的 Windows 服务。 无痛调试。 调试控制台应用程序比调试服务容易得多。 访问 .NET 框架不支持的所有启动和服务恢复设置。 快速开始 创建一个新的控制台应用程序项目。 参考...

    用.NET创建Windows服务的方法第1/2页

    内容包含什么是Windows服务,如何创建、安装和调试它们。会用到System.ServiceProcess.ServiceBase命名空间的类。 什么是Windows服务? Windows服务应用程序是一种需要长期运行的应用程序,它对于服务器环境特别适合...

    Windows内部原理(十一):存储和文件系统

    中间经历了若干个复杂的步骤,包括内核和执行体的初始化,创建系统进程和线程,对象管理器初始化基本对象,I/O管理器枚举设备并安装驱动程序,启动SMSS和WinLogon进程,运行Windows子系统进程。本讲座将解析以上各个...

    windows 内部原理(一)

    中间经历了若干个复杂的步骤,包括内核和执行体的初始化,创建系统进程和线程,对象管理器初始化基本对象,I/O管理器枚举设备并安装驱动程序,启动SMSS和WinLogon进程,运行Windows子系统进程。本讲座将解析以上各个...

Global site tag (gtag.js) - Google Analytics