C# Windows 服务开发并启动

本文详细介绍了如何在Visual Studio中创建Windows服务项目,并部署服务。包括设置服务属性、使用System.Timers命名空间下的Timer组件处理业务逻辑,以及利用InstallUtil工具进行安装与卸载。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1、新建项目选择 Windows-----> Windows Service 即创建 windows service 项目。

 

 

2、在 ProjectInstaller.cs 设计模式下,点右键,选择 "Add Installer" ,点击 ServiceInstaller1 属性中修改 ServiceName 为自己的 service name, StartType 修改为 AutoMatic 即 自动启动,如手动启动则修改为  Manual。

 

 

3、在 ProjectInstaller.cs 设计模式下, 点击  ServiceProcessInstaller1, 在属性中修改  Account 修改为 LocalSystem。

 

 

4、在 Service1.cs 中, OnStart(string[] args) 方法即开始定义自己 windows service 要处理的业务。我觉得一般处理方式是放一个 timer于该Form 中,

(注意:该 timer 为  System.Timers 命名空间下的 Timer, 而非默认的 System.Windows.Forms 命名空间下的 Timer)

然后通过 timer 循环处理事件处理自己的业务。

 

 

5、部署 windows service ,可以使用 visual studio  自带工具 InstallUtil.exe,  installutil yourproject.exe (此处 yourproject.exe 为自己开发的服务名编译后的exe 文件),如果要卸载,则加参数 -u.

 

 

6、一般开发后虽然服务设置为 Automatic ,但首次部署后必须要手动启动下才可,搜索了一下,发现博客园中有人如下解决。

该解决原址:http://www.cnblogs.com/wfwup/archive/2009/01/14/1375382.html

在ProjectInstaller.cs 设计模式下,事件 AfterInstall 事件中加入如下代码便可启动:

  Process p = new Process();
            p.StartInfo.FileName = "cmd.exe";
            p.StartInfo.UseShellExecute = false;
            p.StartInfo.RedirectStandardInput = true;
            p.StartInfo.RedirectStandardOutput = true;
            p.StartInfo.RedirectStandardError = true;
            p.StartInfo.CreateNoWindow = true;
            p.Start();
            string cmdStr = string.Format("sc start {0}", this.serviceInstaller1.ServiceName);
            p.StandardInput.WriteLine(cmdStr);
            p.StandardInput.WriteLine("exit");

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值