1、新建一个Windows Service项目,重命名服务类名
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.ServiceProcess;
using System.Threading;
namespace ServiceTestCS
{
public partial class ServiceTestCS : ServiceBase
{
//安装卸载时,最好用绝对路径哦
//Installutil NASTestCS
//Installutil -u NASTestCS
private const int waitInterval = 200;
private AutoResetEvent stopEvent = new AutoResetEvent(false);
private AutoResetEvent pauseContinueEvent = new AutoResetEvent(false);
private Thread workingThread = null;
public NASTestCS()
{
InitializeComponent();
this.CanPauseAndContinue = true;
this.CanShutdown = true;
}
protected override void OnStart(string[] args)
{
#if DEBUG
/*
//等待调试器,但调试Windows服务时,提示没有加载符号
while (!Debugger.IsAttached)
{
Thread.Sleep(waitInterval);
}
*/
Debugger.Launch();
#endif
workingThread = new Thread(new ThreadStart(MaiLoop));
workingThread.Start();
}
protected override void OnStop()
{
stopEvent.Set();
}
protected override void OnShutdown()
{
stopEvent.Set();
}
protected override void OnPause()
{
pauseContinueEvent.Set();
}
protected override void OnContinue()
{
pauseContinueEvent.Set();
}
protected void MaiLoop()
{
Boolean bEnd = false;
while (!bEnd)
{
//处理你的正常事务
//但要保证下面的代码,可以定期被调用到
//......
//截获停止事件
if(stopEvent.WaitOne(waitInterval))
{
bEnd = true;
break;
}
//截获暂停事件
if (pauseContinueEvent.WaitOne(waitInterval))
{
//等待继续时间
while (!pauseContinueEvent.WaitOne(waitInterval))
{
//少占用一些资源
Thread.Sleep(waitInterval);
//暂停时也可以退出
if (stopEvent.WaitOne(waitInterval))
{
bEnd = true;
break;
}
}
}
}
}
}
}
2、服务设计界面右击,添加Service Installer
配置Service Installer,配置服务类名称,显示名称,启动类型,登录用户,服务依赖等
但如果要可以与桌面交互的话,需要添加代码实现。
双击serviceInstaller,添加下面方法:
using System.Management;
private void serviceInstaller_AfterInstall(object sender, InstallEventArgs e)
{
//要用LocalSystem用户登录才有效哦
ManagementObject wmiService = new ManagementObject(string.Format("Win32_Service.Name='{0}'", this.serviceInstaller.ServiceName));
ManagementBaseObject changeMethod = wmiService.GetMethodParameters("Change");
changeMethod["DesktopInteract"] = true;
ManagementBaseObject OutParam = wmiService.InvokeMethod("Change", changeMethod, null);
}
3、安装与反安装,用命令行实现
rem 安装服务 %PATH_TO_INSTALLUTIL%\installutil.exe %PATH_TO_SERVICE%\NASTestCS.exe rem 卸载服务 %PATH_TO_INSTALLUTIL%\installutil.exe -u %PATH_TO_SERVICE%\NASTestCS.exe