文章内容
2017/11/6 16:00:02,作 者: 黄兵
visual studio express 编写windows service
最近要写一个服务,但是我安装的是visual studio express ,没有Windows service这一项:
之后参考了一下stackoverflow,终于把Windows Sservice写出来了(其实Windows Service就是一个模板),详细步骤如下:
使用的Visual Studio 2013 Express Web,之后新建一个类库,点击属性,更改为控制台应用程序,如下所示:
Key points:
- write a class that inherits from
ServiceBase
- in your
Main()
, useServiceBase.Run(yourService)
- in the
ServiceBase.OnStart
override, spawn whatever new thread etc you need to do the work (Main()
needs to exit promptly or it counts as a failed start)
Sample Code
Very basic template code would be:
Program.cs:
using System;
using System.ServiceProcess;
namespace Cron
{
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
static void Main()
{
System.ServiceProcess.ServiceBase.Run(new CronService());
}
}
}
CronService.cs:
using System;
using System.ServiceProcess;
namespace Cron
{
public class CronService : ServiceBase
{
public CronService()
{
this.ServiceName = "Cron";
this.CanStop = true;
this.CanPauseAndContinue = false;
this.AutoLog = true;
}
protected override void OnStart(string[] args)
{
// TODO: add startup stuff
}
protected override void OnStop()
{
// TODO: add shutdown stuff
}
}
}
CronInstaller.cs:
using System.ComponentModel;
using System.Configuration.Install;
using System.ServiceProcess;
[RunInstaller(true)]
public class CronInstaller : Installer
{
private ServiceProcessInstaller processInstaller;
private ServiceInstaller serviceInstaller;
public CronInstaller()
{
processInstaller = new ServiceProcessInstaller();
serviceInstaller = new ServiceInstaller();
processInstaller.Account = ServiceAccount.LocalSystem;
serviceInstaller.StartType = ServiceStartMode.Manual;
serviceInstaller.ServiceName = "Cron"; //must match CronService.ServiceName
Installers.Add(serviceInstaller);
Installers.Add(processInstaller);
}
}
windows service 不能像控制台程序一样运行,那我们就使用InstallUtil.exe来安装:
InstallUtil.exe的所在目录是:C:\Windows\Microsoft.NET\Framework64\v4.0.30319
之后在CMD窗口运行,如下所示:
将刚才编写的应用程序生成,之后找到生成的程序目录,在CMD窗口安装刚才写的服务,如下所示:
之后看一下“服务”,已经成功安装,如下所示:
参考资料:
How to create windows service in C# manual Install using installutil.exe
How can I make service apps with Visual c# Express?
黄兵个人博客原创。
评论列表