如何创建、安装和调试windows服务

windows服务应用场景:

(1)定时操作数据库,比如定时邮件发送等

(2)在.net Remoting中利用windows服务来做Host(未测试)

创建步骤:
1. 新建一个项目
2. 从一个可用的项目模板列表当中选择Windows服务
3. 打开后台代码,在OnStart方法中加入如下代码段

 public System.Timers.Timer time2;

 protected override void OnStart(string[] args)
        {
             // TODO: 在此处添加代码以启动服务。
              time2 = new System.Timers.Timer();
            time2.Interval = 1000 * 5;
            time2.Elapsed += new System.Timers.ElapsedEventHandler(AddUser);
            time2.Enabled = true;
        }
private void AddUser(object sender, System.Timers.ElapsedEventArgs e)
        {
           
            using (SqlConnection conn = new SqlConnection(@"Data Source=PC-201108111018\SQLEXPRESS;initial catalog=test;uid=sa;pwd=sa"))
            {
                try
                {
                    SqlCommand comm = new SqlCommand("insert into [user] values('服务',100,getdate())", conn);
                    conn.Open();
                    if (comm.ExecuteNonQuery() > 0)
                    {
                        SqlCommand comm2 = new SqlCommand("insert into [log] values('插入成功',getdate())", conn);
                        comm2.ExecuteNonQuery();
                    }
                    else {
                        SqlCommand comm2 = new SqlCommand("insert into [log] values('"+e.+"',getdate())", conn);
                        comm2.ExecuteNonQuery();
                    }
                }
                catch (Exception)
                {
                    SqlCommand comm2 = new SqlCommand("insert into [log] values('插入失败',getdate())", conn);
                    comm2.ExecuteNonQuery();
                }
            }
        }

 4. 将这个服务程序切换到设计视图
 5. 右击设计视图选择“添加安装程序”
 6. 切换到刚被添加的ProjectInstaller的设计视图
 7. 设置serviceInstaller1组件的属性: 
    1) ServiceName = MyService
    2) StartType = Automatic (开机自动运行)
 8. 设置serviceProcessInstaller1组件的属性  Account = LocalSystem
 9. 安装服务:执行命令“InstallUtil.exe MyWindowsService.exe”注册这个服务,使它建立一个合适的注册项。

10. 右击桌面上“我的电脑”,选择“管理”就可以打计算机管理控制台
11. 在“服务和应用程序”里面的“服务”部分里,你可以发现你的Windows服务已经包含在服务列表当中了
12. 右击你的服务选择启动就可以启动你的服务了
13.卸载服务:InstallUtil.exe/u MyWindowsService.exe

14:调试服务,在OnStart方法中加入如下代码段:

 

protected override void OnStart(string[] args)
        {
            #if DEBUG
            Debugger.Launch();     //Launches and attaches a debugger to the process.
            #endif
            // TODO: 在此处添加代码以启动服务。
        
       }

 

 在OnStart启动服务代码下插入断点,在vs菜单中选择“调试”-》“附加到进程”,勾选“显示所有用户的进程”,选择要新安装的要调试的服务,点击“附加”即可。

 

 

原文地址:https://www.cnblogs.com/Loyalty/p/2465788.html