如何使用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 @   Sunny Peng  阅读(1117)  评论(0编辑  收藏  举报
编辑推荐:
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
阅读排行:
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· .NET周刊【3月第1期 2025-03-02】
· 分享 3 个 .NET 开源的文件压缩处理库,助力快速实现文件压缩解压功能!
· Ollama——大语言模型本地部署的极速利器
点击右上角即可分享
微信分享提示