如何使用Windows Service?

(1)      在创建windowsservice程序时,Debug/Release的类型选择为AnyCPU(特别是64位的机器)

(2)      添加安装程序时,会生成两个组件,比如ServiceProcessInstaller1,ServiceInstaller1

(3)      在为service添加安装程序时,安装程序(比如ServiceInstaller1)的Name属性和Service的Name属性要一致

(4)      ServiceProcessInstaller1的Account属性必须设置为LocalSystem

(5)      安装服务时,以管理员身份运行Viusial Studio命令行工具进行安装

安装服务的命令: 

Installutil “程序地址”

(比如:Installutil "D:/Users/SPang/Documents/VisualStudio2010/Projects/WindowsService1/WindowsService1/bin/Debug/WindowsService1.exe")

卸载服务的命令:

Installutil “程序地址” /u

(比如:Installutil "D:/Users/SPang/Documents/VisualStudio2010/Projects/WindowsService1/WindowsService1/bin/Debug/WindowsService1.exe"/u )

(6)      安装完成后启动服务,可以通过我的MyComputer -> Manage -> System Tools -> EventViewer -> Windows Logs-> Application(我的电脑->管理->事件查看器->windows日志->应用程序)查看服务的日志。

(7)      在使用命令时可能出现的错误: 

          i. an attempt was made to load a program withan incorrect format。解决方法:步骤1

          ii. the install failed, and the roll back hasbeen performed。解决方法:步骤4

最简单的一个Windows Service代码示例(VB.NET):

C#代码和这个差不多

Public Class Service1

Protected Overrides Sub OnStart(ByVal args() As String)
' Add code here to start your service. This method should set things
' in motion so your service can do its work.
EventLog.WriteEntry("Start Service")
End Sub

Protected Overrides Sub OnStop()
' Add code here to perform any tear-down necessary to stop your service.
End Sub
End Class

 

posted @ 2010-05-25 16:24  Sunny Peng  阅读(1108)  评论(0编辑  收藏  举报