当前位置:首页 > Windows程序 > 正文

Windows 服务入门指南

2021-03-29 Windows程序

有很多时候,我们需要创建Windows Service。 这篇文章可以算是一个入门指南吧,希望对初学者有帮助.

要创建Windows Service, 首先选择Windows服务项目,如下图:

这里我想创建一个Windows服务,定时的执行一些任务。

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

OnStart :服务启动的时候执行,

OnStop:服务停止的时候执行

为了定时的执行任务,我修改代码如下:

namespace TimeWindowsService { public partial class Service1 : ServiceBase { System.Timers.Timer timer = null; public Service1() { InitializeComponent(); } protected override void OnStart(string[] args) { timer = new System.Timers.Timer(); timer.Elapsed += timer_Elapsed; timer.Interval = 1000; timer.Start(); } void timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e) { Console.WriteLine("Time elapsed"); } protected override void OnStop() { if (timer != null) { timer.Stop(); } } } }

按F5运行代码,会提示:

这代表我们必须先使用Installutil.exe 来安装服务。

当然你可以打开命令行,然后输入命令来安装服务,不过在这里我打算使用外部工具来执行InstallUtil.exe。

其中命令是:C:\Windows\Microsoft.NET\Framework\v4.0.30319\InstallUtil.exe

点击确定,可以发现一个InstallService 命令。

点击InstallService,可以发现屏幕闪了一下,然后又过了,很明显是因为我们的命令出错了。

注意,,我们在添加InstallService的时候,选择的是,所以即使有错误信息,也会一闪而过。

修改InstallService的命令如下:

再次运行InstallService,可以看到:

这代表InstallService 的时候出错了,找不到文件,我们希望它找的是TimeWindowsService.exe,

而不是\bin\debug\TimeWindowsService

所以正确的设置InstallService命令应该是下面这样:

保存,然后运行,结果如下:

还是没有安装成功,因为没有安装程序。

有很多教程会告诉你,需要添加一个像下面这样的类:

using System.Collections; using System.Configuration.Install; using System.ServiceProcess; using System.ComponentModel; namespace WindowsService1 { /// <summary> /// myInstall 的摘要说明。 /// </summary> /// [RunInstaller(true)] public class myInstall : Installer { private ServiceInstaller serviceInstaller; private ServiceProcessInstaller processInstaller; public myInstall() { processInstaller = new ServiceProcessInstaller(); serviceInstaller = new ServiceInstaller(); processInstaller.Account = ServiceAccount.LocalSystem; serviceInstaller.StartType = ServiceStartMode.Automatic; serviceInstaller.ServiceName = "WindowsService1"; Installers.Add(serviceInstaller); Installers.Add(processInstaller); } } }

对于记性不好的人来说,很容易问的一个问题是:VS有提供相关的快捷键吗?,当然,VS提供了。

在Service1.cs 设计页面点击,添加安装程序,vs 就会自动帮你生成一个Installer 的类。

添加的类是:

温馨提示: 本文由Jm博客推荐,转载请保留链接: https://www.jmwww.net/file/69469.html