近期一直比较忙已经很长时间没有更新Blog了,公司又要交什么所谓的技术报告,现把以前写的一下文章重新整理了一下。 相关内容如下:
Windows Service的安装,卸载,启动以及调试
在做
C#
项目时
,
使用到了
Windows Service
。现结合项目就
Windows Service
的相关知识做一下简单介绍。
一.
项目介绍
项目包括
3
个工程:一个
Windows Service
工程,工程名称为
testService
;一个具体的业务处理工程
(dll)
,工程名称为
testProject
;一个安装工程,工程名称为
testServiceSetup
。
二.
Windows Service的安装与卸载以及启动
要想运行一个
Windows Service
程序,首先必须将这个服务程序安装到
Windows
服务控制台中去。如何安装,卸载和启动
Windows Service
程序呢?主要有
2
种方式。
方式一用framwork自带的InstallUtil命令以及net start命令
1)
安装
Service: InstallUtil testService.exe
2)
卸载
Service: InstallUtil /u testService.exe
3)
启动
Service: net start "
服务名称
"(
当然最简单的就是手动启动了
^_^)
方式二就是做一个安装工程
方式二的最大好处就是通过相关设定,安装完服务后可以立马注册
Windows Service
程序到
Windows
服务中去,下面我们详细说明一下如何实现这种处理方式。
1)
为Windows Service工程(testService)添加一个安装工程(testServiceSetup)
2)
右键点击创建的安装工程(testServiceSetup),选择"追加"-->"项目输出",在"添加 项目输出组"对话框中选择"主输出",在"项目"下拉框中选择需要主输出的服务程序即testService。
3)
右键点击创建的安装工程(testServiceSetup)选择"视图"-->"自定义操作",右键点击"自定义操作"添加"自定义操作",
选择应用程序文件夹中的主输出程序
testService
,此时在以下
4
个节点
(
安装,提交,回滚,卸载
)
中都添加了主输出程序
testService
。
4)
编译安装。
安装完毕后你创建的服务已经添加到
Windows
控制台中去了。
5)
启动
Service: net start "
服务名称
"(
当然最简单的就是手动启动了
^_^)
三.
Windows Service的调试
Windows Service
程序不同于一般的应用程序,直接调试是不起作用的。在
.net
环境下怎样才可以实现对
Windows Service
程序的调试呢。
启动
Visual Studio
,打开你的工程
testService
。选择菜单
"
调试
->
进程
"
。在进程窗口里附加你的服务程序
testService.exe
。如果看不到
testService.exe
,请选中
"
显示系统进程
"
。这样就能看到以
system
账号运行的
Service
。如果你已经设置了断点,当
Serice
运行到你设置的断点时,程序就会停下来等待你的调试。
(
说明:只有
Debug
模式下编译的
testService.exe
才可以进行调试
)
。
四.
Onstart()的调试
1) 在方法 Onstart() 里设置 System.Timers.Timer ,然后用 Timer 来延迟启动服务。
1) 在方法 Onstart() 里设置 System.Timers.Timer ,然后用 Timer 来延迟启动服务。
延迟的时间由你进入调试状态的时间来决定。可以设置为
5
秒。当然服务启动后应停
止
Timer(
设置
Timer.Enable=false).
2) 你的服务程序可以进行控制台间的交互。假设你的服务程序满足了如下条件:
2) 你的服务程序可以进行控制台间的交互。假设你的服务程序满足了如下条件:
public class ManagedWindowsService : System.ServiceProcess.ServiceBase
{
// designer and user generated methods and properties
public static int main(String[] args)
{
ServiceBase.Run( new MangedWindowsService() );
}
}
也就是说类似与一个应用程序。只需要添加如下语句就可以对
Onstart()
方法进行调试了。
public static int main(String[] args)
{
(new ManagedWindowsService()).OnStart();
ServiceBase.Run( new MangedWindowsService() );
}