引言 

Window Service通常用于寄宿WCF服务或者定时作业.下面记录一下它的用法.

创建

创建Window Service项目后,可以看到Program和Service1类.Program是程序的主入口,而Service1则是我们逻辑实现的主要地方 ,两个关键方法是OnStart和OnStop,用于实现服务启动和结束时的逻辑.

安装

在Service1类的设计界面上右击,选择添加安装程序,就可以完成了安装程序的创建.

Nlog

Window Service作为一个后台程序,发生了什么错误很难获取的信息的,所以需要做个日志记录.下面做个示例,每3秒输出日志记录.

1.打开NuGet程序包管理界面,输入Nlog搜索,安装其中的Nlog和Nlog Configuration,接着在NLog.config做下修改,如下

<target xsi:type="File" name="f" fileName="${basedir}/logs/${shortdate}.log"
layout="${longdate} ${uppercase:${level}} ${message}" /> <target xsi:type="Console" name="c" layout="[${longdate}][${level:uppercase=true}][${logger}]${message}${exception}" /> </targets> <rules
<logger name="*" minlevel="Debug" writeTo="f,c" />
</rules>

2.在Service1中使用Timer和Nlog类,实现每3秒输出日志记录,如下

  public partial class Service1 : ServiceBase
{
readonly Logger logger = LogManager.GetCurrentClassLogger();
readonly Timer timer=new Timer();
public Service1()
{
InitializeComponent();
}
protected override void OnStart(string[] args)
{
timer.AutoReset = true;
timer.Interval = ; //单位毫秒
timer.Elapsed+=timer_Elapsed;
timer.Start();
}
protected override void OnStop()
{
timer.Stop();
}
private void timer_Elapsed(object sender, ElapsedEventArgs e)
{
logger.Info(DateTime.Now.ToShortTimeString());
}
//下面两个方法是为了方便调试而创建
public void Start()
{
OnStart(null); }
public void Stop()
{
OnStop();
}
}

部署

下面是安装和卸载脚本,分别保存成Bat文件,放在程序的根目录就可以.

@echo 安装服务
set svc_file=%cd%\WindowsServiceDemo.exe
sc create Service1 binpath= "%svc_file%" displayName= "Service1" depend= tcpip start= auto
net start Service1
@pause
@exit @echo 卸载服务
net stop Service1
sc delete Service1
@pause
@exit

调试
    VS貌似没有提供给Window Service调试的工具,要测试只能通过实际部署才能看到效果,但是可以利用TopShell寄宿服务来达到调试的目的.

1. http://topshelf-project.com/   可以下到最新的类库

2.新建一个控制台程序,引用上面的服务,TopShell,Nlog,就可以编码了,如下

class Program
{
static void Main(string[] args)
{
HostFactory.Run(x =>
{
x.UseNLog(); x.Service<Service1>(s =>
{
s.ConstructUsing(name => new Service1());
s.WhenStarted(tc => tc.Start());
s.WhenStopped(tc => tc.Stop());
}); x.SetServiceName("Service1");
x.SetDisplayName("Service1");
x.SetDescription("每3秒记录日志");
x.RunAsLocalSystem();
x.StartAutomatically();
}); }

3.运行控制台程序,可以看到

小结

本文简单介绍了Window Service从创建到调试的步骤.如有更好的建议,请不吝指教.

参考资料

C# 编写Windows Service(windows服务程序)

使用Topshelf创建Windows 服务

NLog文章系列——系列文章目录以及简要介绍

【Window Service】关于Window Service的两三事的更多相关文章

  1. 在Activity,Service,Window中监听Home键和返回键的一些思考,如何把事件传递出来的做法!

    在Activity,Service,Window中监听Home键和返回键的一些思考,如何把事件传递出来的做法! 其实像按键的监听,我相信很多人都很熟练了,我肯定也不会说这些基础的东西,所以,前期,还是 ...

  2. [PWA] 9. Service worker registerion && service work's props, methods and listeners

    In some rare cases, you need to ask user to refresh the browsser to update the version. Maybe becaus ...

  3. service: no such service mysqld 与MySQL的开启,关闭和重启

    1.问题原因与解决办法 因为修改了MySQL临时文件的目录后,使用service mysqld restart重启MySQL出现如下错误: service: no such service mysql ...

  4. Failed to stop iptables.service: Unit iptables.service not loaded.

    redhat 7 [root@lk0 ~]# service iptables stop Redirecting to /bin/systemctl stop iptables.service Fai ...

  5. window.onload和window.document.readystate的探究

    在编写前端页面的时候,我们时常需要对页面加载的状态进行判断,以便进行相应的操作. 比如在移动端,时常需要在页面完全加载完成之前,先显示一个loading的图标,等待页面完成加载完成后,才显示出真正要展 ...

  6. window.location.href = window.location.href 跳转无反应 a 超链接 onclick 点击跳转无反应

    错误写法 , 主要是在 href="#"这里 <a href="#" id="send" onclick="return b ...

  7. window.parent与window.openner区别介绍

    今天总结一下js中几个对象的区别和用法: 首先来说说 parent.window与top.window的用法 "window.location.href"."locati ...

  8. window.parent 与 window.opener

    window.parent针对iframe,window.opener针对window.open 父页面parent.jsp: <%@ page language="java" ...

  9. window.location和window.open

    window.location和window.open的区别 window.location = "http://www.baidu.com" 跳转后有后退功能 window.lo ...

  10. JavaScript(Iframe、window.open、window.showModalDialog)父窗口与子窗口之间的操作

    一.Iframe 篇 公共部分 //父对象得到子窗口的值 //ObjectID是窗口标识,ContentID是元素ID function GetValue(ObjectID,ContentID) { ...

随机推荐

  1. 重写toString方法

    当你要读取关于对象的一些有用细节时,可以在对象上调用toString(). 如,当把一个对象引用传递给System.out.println();时,该对象的toString()方法被调用. Java中 ...

  2. HDFS权限

    1.1 超级用户 启动namenode服务的用户就是超级用户, 该用户的组是supergroup 1.2 文件权限管理   1.2.1 创建时的owner和group 文件或者目录被创建之时,服从BS ...

  3. 深度学习2--安装opencv3.1

    1\opencv的安装参考视频 2\ 以下内容来自:http://blog.csdn.net/l18930738887/article/details/54696148 本人因为被坑过,所以建议各位最 ...

  4. dockfile

    dockerfile是对镜像的描述 新建一个dockfile文件 docker inspect

  5. CSS清除浮动使父级元素展开的三个方法

    点评:一个没有设置高度的容器div内如果存在浮动元素(即使用了属性float:left或者float:right),那么该父级元素会无法展开,下面举个例子为大家详细介绍下,希望对大家有所帮助 一个没有 ...

  6. list列表、tuple元组、range常用方法总结

    list 列表(数组),是可迭代对象,列表是可变的所以列表的方法都是在列表本身更改的.里面看可以放各种数据类型的数据,可存储大量数据 连接列表可以使用 + 或 extend() a = [1, 3, ...

  7. 吐槽 MySQL数据库jdbc操作,varchar类型占位符问题——单引号造孽

    很长时间不写代码动手能力明显下降很多常见的错误还是经常发生,今天吐血了一次. 简单的坑总是要多跳几次才能甘心.很清晰的记得大学的时候在此坑差点闷死,现在又跳进这个坑了,搞了半天终于知道错在哪里. St ...

  8. Linux基本命令 压缩命令

    1.压缩命令 ================================================================================== 命令名称:gzip ...

  9. awk的getline命令

    原文出处:生活费的博客,http://www.cnblogs.com/276815076/archive/2011/12/05/2276625.html#undefined  两种情况:getline ...

  10. 12个提问频率最高的php面试题

    你是否正在准备寻找一份PHP开发的工作,并且也在寻找一些关于PHP的面试题及答案?本文为大家分享了一些被提问频率最高的11个PHP面试题,以及对应的常规回答,每个公司都有自己的面试标准,面试和问题是完 ...