Windows服务的创建、安装、卸载

1.新建Window服务项目

Windows服务的创建、安装、卸载

2.添加安装配置文件

Windows服务的创建、安装、卸载

3.serviceProcessInstaller1右键属性,设置Account属性为LocalSystem。

serviceInstaller1右键属性,设置Description、DisplayName、StartType。

这些设置在安装后的服务中可以看到。

cmd下输入services.msc,可以看到系统的服务。

Description:为服务中显示的描述信息。

DisplayName:为服务名称。

StartType:启动类型,常用的有手动(Manual)、自动(Automatic)。

设置好后,点击保存。

4.编写服务执行的代码

双击Services1.cs,右键查看代码。

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.ServiceProcess;
using System.Text; namespace WindowsService1
{
public partial class Service1 : ServiceBase
{
public Service1()
{
InitializeComponent();
} protected override void OnStart(string[] args)
{
} protected override void OnStop()
{
}
}
}

显示了服务开始事件、停止事件。

我们如果要实现定时任务的话,可以在构造方法中使用Timer。

public Service1()
{
InitializeComponent(); Timer timer = new Timer();
timer.Interval = * * AppHelper.Interval;
timer.Enabled = true;
timer.Elapsed += TimedEvent;
}
 private void TimedEvent(object sender, System.Timers.ElapsedEventArgs e)
{
}

5.至此一个服务创建完成,下来介绍服务的安装。
找到服务项目bin/debug下的文件,Copy到D:\WindowsService下。

当然这个路径是任意的,执行安装任务、卸载任务的时候需要使用。

去C:\Windows\Microsoft.NET\Framework64\v4.0.30319下找到InstallUtil.exe这个文件。

因为我用的64位的系统,32位前往C:\Windows\Microsoft.NET\Framework\v4.0.30319中找这个文件。

将这个安装、卸载文件Copy到D:\WindowsService下。

所有准备工作做好了,下来说安装。

管理员身份运行cmd,之后执行D:\WindowsService\InstallUtil.exe D:\WindowsService\WindowsService1.exe 回车

cmd下输入services.msc根据名称就可以看到我们安装的服务了。

服务安装好运行起来后,我们想要用vs调试下服务代码怎么操作了?

选择vs上的debug(调试)-》附加到进程-》勾选显示所有用户的进程,这个时候就能看到我们安装的进程了,选择这个进程。

对于定时任务,定时器执行的事件处设置好断点,等到定时器间隔到时,就会看到程序走到断点处了。

6.服务卸载

管理员身份运行cmd,之后执行D:\WindowsService\InstallUtil.exe -u D:\WindowsService\WindowsService1.exe 回车

上一篇:JQuery.Ajax()的data参数类型


下一篇:WCF例子