-
我们将研究如何创建一个作为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自动生成的。
001.
using
System;
002.
003.
using
System.Collections;
004.
005.
using
System.ComponentModel;
006.
007.
using
System.Data;
008.
009.
using
System.Data.SqlClient;
010.
011.
using
System.Diagnostics;
012.
013.
using
System.ServiceProcess;
014.
015.
namespace
CodeGuru.MyWindowsService
016.
017.
{
018.
019.
public
class
MyService : System.ServiceProcess.ServiceBase
020.
021.
{
022.
023.
private
System.Timers.Timer timer1;
024.
025.
/// <remarks>
026.
027.
/// Required designer variable.
028.
029.
/// </remarks>
030.
031.
private
System.ComponentModel.Container components =
null
;
032.
033.
public
MyService()
034.
035.
{
036.
037.
// This call is required by the Windows.Forms
038.
039.
// Component Designer.
040.
041.
InitializeComponent();
042.
043.
}
044.
045.
// The main entry point for the process
046.
047.
static
void
Main()
048.
049.
{
050.
051.
System.ServiceProcess.ServiceBase[] ServicesToRun;
052.
053.
054.
055.
ServicesToRun =
new
System.ServiceProcess.ServiceBase[]
056.
057.
{
new
MyService() };
058.
059.
System.ServiceProcess.ServiceBase.Run(ServicesToRun);
060.
061.
}
062.
063.
/// <summary>
064.
065.
/// Required method for Designer support - do not modify
066.
067.
/// the contents of this method with the code editor.
068.
069.
/// </summary>
070.
071.
private
void
InitializeComponent()
072.
073.
{
074.
075.
this
.timer1 =
new
System.Timers.Timer();
076.
077.
((System.ComponentModel.ISupportInitialize)
078.
079.
(
this
.timer1)).BeginInit();
080.
081.
//
082.
083.
// timer1
084.
085.
//
086.
087.
this
.timer1.Interval = 30000;
088.
089.
this
.timer1.Elapsed +=
090.
091.
new
System.Timers.ElapsedEventHandler(
this
.timer1_Elapsed);
092.
093.
//
094.
095.
// MyService
096.
097.
//
098.
099.
this
.ServiceName =
"My Sample Service"
;
100.
101.
((System.ComponentModel.ISupportInitialize)
102.
103.
(
this
.timer1)).EndInit();
104.
105.
}
106.
107.
/// <summary>
108.
109.
/// Clean up any resources being used.
110.
111.
/// </summary>
112.
113.
protected
override
void
Dispose(
bool
disposing )
114.
115.
{
116.
117.
if
( disposing )
118.
119.
{
120.
121.
if
(components !=
null
)
122.
123.
{
124.
125.
components.Dispose();
126.
127.
}
128.
129.
}
130.
131.
base
.Dispose( disposing );
132.
133.
}
134.
135.
/// <summary>
136.
137.
/// Set things in motion so your service can do its work.
138.
139.
/// </summary>
140.
141.
protected
override
void
OnStart(
string
[] args)
142.
143.
{
144.
145.
this
.timer1.Enabled =
true
;
146.
147.
this
.LogMessage(
"Service Started"
);
148.
149.
}
150.
151.
152.
153.
/// <summary>
154.
155.
/// Stop this service.
156.
157.
/// </summary>
158.
159.
protected
override
void
OnStop()
160.
161.
{
162.
163.
this
.timer1.Enabled =
false
;
164.
165.
this
.LogMessage(
"Service Stopped"
);
166.
167.
}
168.
169.
/*
170.
171.
* Respond to the Elapsed event of the timer control
172.
173.
*/
174.
175.
private
void
timer1_Elapsed(
object
sender,
176.
177.
System.Timers.ElapsedEventArgs e)
178.
179.
{
180.
181.
this
.LogMessage(
"Service Running"
);
182.
183.
}
184.
185.
/*
186.
187.
* Log specified message to database
188.
189.
*/
190.
191.
private
void
LogMessage(
string
Message)
192.
193.
{
194.
195.
SqlConnection connection =
null
;
196.
197.
SqlCommand command =
null
;
198.
199.
try
200.
201.
{
202.
203.
connection =
new
SqlConnection(
204.
205.
"Server=localhost;Database=SampleDatabase;Integrated
206.
207.
Security=
false
;User Id=sa;Pass<a href=
"http://www.it165.net/edu/ebg/"
target=
"_blank"
class
=
"keylink"
>word</a>=;");
208.
209.
command =
new
SqlCommand(
210.
211.
"INSERT INTO MyServiceLog (vc_Status, dt_Created)
212.
213.
VALUES (’
" + Message + "
’,getdate())", connection);
214.
215.
connection.Open();
216.
217.
int
numrows = command.ExecuteNonQuery();
218.
219.
}
220.
221.
catch
( Exception ex )
222.
223.
{
224.
225.
System.Diagnostics.Debug.WriteLine(ex.Message);
226.
227.
}
228.
229.
finally
230.
231.
{
232.
233.
command.Dispose();
234.
235.
connection.Dispose();
236.
237.
}
238.
239.
}
240.
241.
}
242.
243.
}
安装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这个源文件内。
001.
using
System;
002.
003.
using
System.Collections;
004.
005.
using
System.ComponentModel;
006.
007.
using
System.Configuration.Install;
008.
009.
namespace
CodeGuru.MyWindowsService
010.
011.
{
012.
013.
/// <summary>
014.
015.
/// Summary description for ProjectInstaller.
016.
017.
/// </summary>
018.
019.
[RunInstaller(
true
)]
020.
021.
public
class
ProjectInstaller :
022.
023.
System.Configuration.Install.Installer
024.
025.
{
026.
027.
private
System.ServiceProcess.ServiceProcessInstaller
028.
029.
serviceProcessInstaller1;
030.
031.
private
System.ServiceProcess.ServiceInstaller serviceInstaller1;
032.
033.
/// <summary>
034.
035.
/// Required designer variable.
036.
037.
/// </summary>
038.
039.
private
System.ComponentModel.Container components =
null
;
040.
041.
public
ProjectInstaller()
042.
043.
{
044.
045.
// This call is required by the Designer.
046.
047.
InitializeComponent();
048.
049.
// TODO: Add any initialization after the InitComponent call
050.
051.
}
052.
053.
#region Component Designer generated code
054.
055.
/// <summary>
056.
057.
/// Required method for Designer support - do not modify
058.
059.
/// the contents of this method with the code editor.
060.
061.
/// </summary>
062.
063.
private
void
InitializeComponent()
064.
065.
{
066.
067.
this
.serviceProcessInstaller1 =
new
068.
069.
System.ServiceProcess.ServiceProcessInstaller();
070.
071.
this
.serviceInstaller1 =
new
072.
073.
System.ServiceProcess.ServiceInstaller();
074.
075.
//
076.
077.
// serviceProcessInstaller1
078.
079.
//
080.
081.
this
.serviceProcessInstaller1.Account =
082.
083.
System.ServiceProcess.ServiceAccount.LocalSystem;
084.
085.
this
.serviceProcessInstaller1.Pass<a href=
"http://www.it165.net/edu/ebg/"
target=
"_blank"
class
=
"keylink"
>word</a> =
null
;
086.
087.
this
.serviceProcessInstaller1.Username =
null
;
088.
089.
//
090.
091.
// serviceInstaller1
092.
093.
//
094.
095.
this
.serviceInstaller1.ServiceName =
"My Sample Service"
;
096.
097.
this
.serviceInstaller1.StartType =
098.
099.
System.ServiceProcess.ServiceStartMode.Automatic;
100.
101.
//
102.
103.
// ProjectInstaller
104.
105.
//
106.
107.
this
.Installers.AddRange(
new
108.
109.
System.Configuration.Install.Installer[]
110.
111.
{
this
.serviceProcessInstaller1,
this
.serviceInstaller1});
112.
113.
}
114.
115.
#endregion
116.
117.
}
118.
119.
}
用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服务属性来设置。
如何创建、安装和调试Windows服务
最新推荐文章于 2023-06-18 22:40:35 发布