引言 

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. pgAgent设定定时备份

    PostgreSQL定时自动备份 简介 PostgreSQL数据库中未提供数据库的定时备份功能,所以需要结合备份和定时job功能来共同实现. 这里我选取了2种定时job方式,crontab是Linux ...

  2. Python爬虫:爬取自己博客的主页的标题,链接,和发布时间

    代码 # -*- coding: utf-8 -*- """ ------------------------------------------------- File ...

  3. numpy的random模块详细解析

    随机抽样 (numpy.random) 简单的随机数据 rand(d0, d1, ..., dn) 随机值 >>> np.random.rand(3,2) array([[ 0.14 ...

  4. Google Cloud Platfrom中使用Linux VM

    Linkes https://cloud.google.com/compute/docs/quickstart-linuxhttps://console.cloud.google.com/comput ...

  5. vimium的使用介绍和基本用法

    vimium是chrome浏览器的一个插件,fq去chrome应用商店搜索vimium,下载安装 纯键盘操作,脱离了鼠标,提高效率 核心是f,安装好vimium后只需要按f,输入对应的编号就能进入相应 ...

  6. (C#)ListView双击Item事件

    /// <summary> /// 双击选择播放列表项进行播放 /// </summary> /// <param name="sender"> ...

  7. LDA主题模型三连击-入门/理论/代码

    目录 概况 为什么需要 LDA是什么 LDA的应用 gensim应用 数学原理 预备知识 抽取模型 样本生成 代码编写 本文将从三个方面介绍LDA主题模型--整体概况.数学推导.动手实现. 关于LDA ...

  8. iOS 快速遍历 效率分析 for loop for in enumerateBlock 适用条件

    test1 简单遍历 结论: 当数组数据量很小 时候 for loop 和 for in 效率不相上下,随着数据量增长for in 快速枚举的优势 明显 如果需要知道 索引可用 enumrateBlo ...

  9. 012_Eclipse中使用 HDFS URL API 事例介绍

    本事例其实和使用hdfs FileSystem API差不多,FileSystem API也是通过解释成URL在hdfs上面执行的,性质相同,但是实际中用 的fFileSystem会多一点,源码如下: ...

  10. 在树莓派上用Python控制LED

    所需材料 一个已经安装配置好了的树莓派 连接控制树莓派所用的其他必须设备 200Ω电阻 x 8 led x 8 面包板及连接线若干 电路连接 电路图 按照电路图所示,在面包板上进行连接. 编写程序 安 ...