用C#创建Windows(NT)服务

来源:互联网 发布:shell编程入门 pdf 编辑:程序博客网 时间:2024/05/28 23:12
<script type="text/javascript"><!--google_ad_client = "pub-2947489232296736";/* 728x15, 创建于 08-4-23MSDN */google_ad_slot = "3624277373";google_ad_width = 728;google_ad_height = 15;//--></script><script type="text/javascript"src="http://pagead2.googlesyndication.com/pagead/show_ads.js"></script>
<script type="text/javascript"><!--google_ad_client = "pub-2947489232296736";/* 160x600, 创建于 08-4-23MSDN */google_ad_slot = "4367022601";google_ad_width = 160;google_ad_height = 600;//--></script><script type="text/javascript"src="http://pagead2.googlesyndication.com/pagead/show_ads.js"></script>
Windows服务在Visual Studio 以前的版本中叫NT服务,在VS.net启用了新的名称。用Visual C# 创建Windows服务不是一件困难的事,本文就将指导你一步一步创建一个Windows服务并使用它。这个服务在启动和停止时,向一个文本文件中写入一些文字信息。这个小技巧来自于MSDN,但是现在程序编写的更加清晰,并且你可以根据你的需要修改它。可下载工程文件包:mcWinService.zip。
第一步:创建服务框架
创建一个新的 Windows 服务,可以从Visual C# 工程中选取 Windows 服务Windows Service)选项,给工程一个新文件名,然后点击 OK。结果看起来是这样的:


你可以看到,向导向工程文件中增加WebService1.cs类:


将ServiceName(服务名)设置成你自己需要的名字,这样在测试期间就更容易识别你的服务,也可以通过编写代码来设置这个属性,方法是this.ServiceName = "mcWinService":


向导在WebService1.cs中增加的默认代码。
第二步:向服务中增加功能
在 WebService1.cs中我们可以看到,有两个被忽略的函数 OnStart和OnStop。

OnStart函数在启动服务时执行,OnStop函数在停止服务时执行。在这里,当启动和停止服务时,向一个文本文件中写入一些文字信息,代码如此。
第三步:安装和运行服务
这个应用程序最后生成一个exe文件mcWinService.exe。要注册这个服务,你需启动开始菜单中的命令行按如下方式调用installutil:installutil C:/mcWebService/bin/Debug/mcWebService.exe。要卸载服务,使用 /u 选项:installutil /u C:/mcWebService/bin/Debug/mcWebService.exe。

第四步:启动和停止服务
在桌面用右键点击图标“我的电脑”选择管理菜单项(Manage),然后启动“服务和应用程序(Services and Applications)”中的服务(Services);你也可以直接从开始菜单中选择管理工具中的计算机管理(Computer ManagemeNT)进入服务。这样你就能看到服务 mcWinService,右键单击弹出菜单中有启动和停止选项。


第五步:测试服务
转到 temp 目录中,看看文本文件是否存在,有没有写入内容。

创建Windows(NT)服务';return true">
<script type="text/javascript"><!--google_ad_client = "pub-2947489232296736";/* 728x15, 创建于 08-4-23MSDN */google_ad_slot = "3624277373";google_ad_width = 728;google_ad_height = 15;//--></script><script type="text/javascript"src="http://pagead2.googlesyndication.com/pagead/show_ads.js"></script>
<script type="text/javascript"><!--google_ad_client = "pub-2947489232296736";/* 160x600, 创建于 08-4-23MSDN */google_ad_slot = "4367022601";google_ad_width = 160;google_ad_height = 600;//--></script><script type="text/javascript"src="http://pagead2.googlesyndication.com/pagead/show_ads.js"></script>
原创粉丝点击