C# Windows 服务开发并启动

来源:互联网 发布:c4d r18 mac版下载 编辑:程序博客网 时间:2024/05/21 06:56

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");