基本参照使用C#创建Windows服务,添加了部分内容

目录

概念

创建Windows Service

可视化管理Windows Service

调试

示例代码

概念

Windows服务是运行在windows后台指定用户下(默认System)的应用程序,它没有标准的UI界面

可以设置服务是否与操作系统一起启动,一起关闭。支持三种方式:1)自动启动2)手动启动3)禁用

创建Windows Service

选择C#标签的Windows Service项目,并创建





初始结构目录如下



修改Service1为TimingService

双击TimingService.cs,如图所示



点击末尾的switch to code view进入代码编辑页面

public partial class TimingService : ServiceBase
{
public TimingService()
{
InitializeComponent();
} protected override void OnStart(string[] args)
{
} protected override void OnStop()
{
}
}

在OnStart和OnStop方法中写上服务启动、停止需要完成的工作

这里我们写一个计时器,每分钟录入一条日志,在此不赘述,可以看示例代码了解

在设计界面右键菜单栏,点击Add Installer



出现两个组件,serviceProcessInstaller1serviceInstaller1,对它们的属性进行修改

serviceInstaller1



ServiceName改为TimingService,是在windows service列表里面的服务名称

Description改为"一个计时器",这里设置的是在windows service列表里面的服务描述

StartType默认为Manual(手动)

相关资料:

ServiceInstaller Class

serviceProcessInstaller1



将Account改为LocalSystem

右键项目点击生成,在\bin\Debug目录下生成MyWindowsService.exe

至此,Windows Service创建完毕

相关资料:

ServiceProcessInstaller Class

可视化管理Windows Service

创建一个Windows Form项目MyWindowsService.Client



在窗体内添加四个按钮,分别为安装服务、启动服务、停止服务及卸载服务



引入System.ServiceProcess.dll和System.Configuration.Install.dll,完善相关功能

//需要引用MyWindowsService项目
string serviceFilePath = $"{Application.StartupPath}\\MyWindowsService.exe";
//这里是设置的serviceName,不是项目名称或者生成的exe的名称
string serviceName = "TimingService"; /// <summary>
/// 安装服务
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void InstallButton_Click(object sender, EventArgs e)
{
if (this.IsServiceExisted(serviceName))
this.UninstallService(serviceName);
this.InstallService(serviceFilePath);
} /// <summary>
/// 启动服务
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void StartButton_Click(object sender, EventArgs e)
{
if (this.IsServiceExisted(serviceName))
this.ServiceStart(serviceName);
} /// <summary>
/// 停止服务
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void StopButton_Click(object sender, EventArgs e)
{
if (this.IsServiceExisted(serviceName)) this.ServiceStop(serviceName);
} /// <summary>
/// 卸载服务
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void UninstallButton_Click(object sender, EventArgs e)
{
if (this.IsServiceExisted(serviceName))
{
this.ServiceStop(serviceName);
this.UninstallService(serviceFilePath);
}
} //判断服务是否存在
private bool IsServiceExisted(string serviceName)
{
ServiceController[] services = ServiceController.GetServices();
foreach (ServiceController sc in services)
{
if (sc.ServiceName.ToLower() == serviceName.ToLower())
{
return true;
}
}
return false;
} //安装服务
private void InstallService(string serviceFilePath)
{
using (AssemblyInstaller installer = new AssemblyInstaller())
{
installer.UseNewContext = true;
installer.Path = serviceFilePath;
IDictionary savedState = new Hashtable();
installer.Install(savedState);
installer.Commit(savedState);
}
} //卸载服务
private void UninstallService(string serviceFilePath)
{
using (AssemblyInstaller installer = new AssemblyInstaller())
{
installer.UseNewContext = true;
installer.Path = serviceFilePath;
installer.Uninstall(null);
}
}
//启动服务
private void ServiceStart(string serviceName)
{
using (ServiceController control = new ServiceController(serviceName))
{
if (control.Status == ServiceControllerStatus.Stopped)
{
control.Start();
}
}
} //停止服务
private void ServiceStop(string serviceName)
{
using (ServiceController control = new ServiceController(serviceName))
{
if (control.Status == ServiceControllerStatus.Running)
{
control.Stop();
}
}
}

为了后续管理服务方便,在MyWindowsService.Client引用MyWindowsService

获得管理员权限

需要使用Administrator的权限才能安装服务

在MyWindowsService.Client项目中右键添加文件应用程序清单



将原来的内容

<requestedExecutionLevel level="asInvoker" uiAccess="false" />

改为下面的内容

<requestedExecutionLevel level="requireAdministrator" uiAccess="false" />

以管理员身份启动程序的相关资料:

How do I force my .NET application to run as administrator?

之后重新生成MyWindowsService.Client,在\bin\Debug文件夹下打开MyWindowsService.Client.exe

使用MyWindowsService.Client.exe安装并启动MyWindowsService.exe



可以右键服务点击属性进行管理

调试

很多种方式,

1.添加一个控制台程序调用业务方法调试

2.打日志调试

3.附加到进程调试

4.官方给的方式,很简单

如何:调试 Windows 服务应用程序

1、3、4适合跟进调试,2适合长期测试并查看问题

示例代码

示例代码

参考资料

如何:创建 Windows 服务

使用C#创建Windows服务

最新文章

  1. python 数据类型 --- 集合
  2. windows下用visual studio code 调试go代码
  3. WCF入门教程(二)如何创建WCF服务
  4. 《JavaScript高级程序设计》读书笔记--前言
  5. libcurl 安装使用一
  6. WordPress主题制作教程2:导航菜单制作
  7. C# unsafe code
  8. OCA读书笔记(1) - 浏览Oracle数据库架构
  9. C++builder编译别人工程报错
  10. 远程Get,Post请求工具类
  11. 用keras作CNN卷积网络书本分类(书本、非书本)
  12. maven工程 java 实现文件上传 SSM ajax异步请求上传
  13. kafka概念使用简介注意点
  14. [bzoj1901]动态区间k大
  15. connect socket的超时设置
  16. SQL导出数据到EXCEL的问题
  17. CountDownLatch &amp; CyclicBarrier
  18. 吴裕雄 31-MySQL 导出数据
  19. MFC函数—CWinApp::LoadStdProfileSettings
  20. 数组slice方法

热门文章

  1. 修复wecenter移动版description首页描述一样问题
  2. 2019牛客暑期多校训练营(第八场)A:All-one Matrices(广告牌问题 单调队列)
  3. CF632E Thief in a Shop 和 CF958F3 Lightsabers (hard)
  4. 【Java】Java环境变量配置
  5. Angular、React、Vue是什么?
  6. kvo与runtime
  7. Weltanschauung--世界观是人类知觉的基础架构
  8. Tips on C/C++
  9. linux学习10 Linux目录结构和根文件系统全面讲解
  10. pipelinewise 基于singer 指南的的数据pipeline 工具