.net服务使用笔记(原创)

最近有个项目需要使用windows 服务 来做

(其实原来也有很多项目有这个需求 只是偷懒用windows应用程序来做了   必须登录才能运行)

这一块 一直 心存遗憾 这一次 决心要用 真正的windows 服务 来做

第一步: 添加windows 服务

第二步: 在windows 服务  设计页面上  点击右键 (安装服务)  将会生成一个新的安装文件(ProjectInstaller.cs)

 

using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration.Install;
using System.Linq;
using System.ServiceProcess;


namespace heartbeat
{
    [RunInstaller(true)]
    public partial class ProjectInstaller : Installer
    {
        /// <summary>
        /// 初始化对象
        /// </summary>
        private ServiceInstaller sInstall;
        private ServiceProcessInstaller sProcessInstall;
        public ProjectInstaller()
        {
            sInstall = new ServiceInstaller();
            sProcessInstall = new ServiceProcessInstaller();
            sProcessInstall.Account = ServiceAccount.LocalSystem;
            sInstall.StartType = ServiceStartMode.Automatic;
            sInstall.ServiceName = "Service1"; //这个服务名必须和步骤1中的服务名相同。 
            sInstall.DisplayName = "移动采编接口服务";
            sInstall.Description = "移动采编接口的心跳服务";
            Installers.Add(sInstall);
            Installers.Add(sProcessInstall);
        }

    }
}

第三步: 在ProjectInstaller.cs 文件的 设计界面上 有2个图标 可以分别点击右键 设置属性

第四步: 定时器的添加

          private System.Timers.Timer timer1;

          protected override void OnStart(string[] args)
        {
            this.timer1 = new System.Timers.Timer(1000 * 5);
            this.timer1.Enabled = true;
            this.timer1.Elapsed += this.timer_Main_Tick;
            this.timer1.Start();
        }

第五步: 将服务进行部署

          将 InstallUtil.exe 复制到您的debug目录下面

        在工程的debug目录下面 建立   注册.bat (installutil  heartbeat.exe) 和 取消注册.bat (installutil  heartbeat.exe /u)

第六步: 调试

      首先将服务启动

      在开发环境里面  菜单/调试/附加到进程 (显示所有用户的进程) 选择您的进程

      (例如 暂停里面有断点)

     点击服务的暂停 会进行调试

       

posted @ 2012-03-27 10:51  郑文亮  阅读(449)  评论(0编辑  收藏  举报