博客
关于我
使用Topshelf 5步创建Windows 服务
阅读量:450 次
发布时间:2019-03-06

本文共 1942 字,大约阅读时间需要 6 分钟。

简要的介绍了创建Windows服务的另一种方法,老外的一篇文章通过5个步骤详细的介绍使用使用Topshelf创建Windows 服务。是一个开源的跨平台的宿主服务框架,支持Windows和Mono,只需要几行代码就可以构建一个很方便使用的服务宿主。

1、Topshelf的代码托管在,可以在这里下载到最新的代码。

2、使用Visual Studio创建一个控制台应用程序引用程序集TopShelf.dll 合log4net.dll 。

3、创建一个简单的服务类,里面包含两个方法Start和Stop,这个服务只是演示代码,所以我们每隔5秒输出一个日志。

using System;
using System.Timers;
using log4net;
namespace SampleWindowsService
{
public class SampleService
{
private Timer _timer = null;
readonly ILog _log = LogManager.GetLogger(typeof(SampleService));
public SampleService()
{
double interval = 5000;
_timer = new Timer(interval);
_timer.Elapsed += new ElapsedEventHandler(OnTick);
}
protected virtual void OnTick(object sender, ElapsedEventArgs e)
{
_log.Debug("Tick:" + DateTime.Now.ToLongTimeString());
}
public void Start()
{
_log.Info("SampleService is Started");
_timer.AutoReset = true;
_timer.Enabled = true;
_timer.Start();
}
public void Stop()
{
_log.Info("SampleService is Stopped");
_timer.AutoReset = false;
_timer.Enabled = false;
}
}
}
4、在Main方法中使用Topshelf宿主我们的服务,主要是告诉Topshelf如何设置我们的服务的配置和启动和停止的时候的方法调用。
using System.IO;
using log4net.Config;
using Topshelf;
namespace SampleWindowsService
{
class Program
{
static void Main(string[] args)
{
XmlConfigurator.ConfigureAndWatch(
new FileInfo(".\\log4net.config"));
var host = HostFactory.New(x =>
{
x.EnableDashboard();
x.Service<SampleService>(s =>
{
s.SetServiceName("SampleService");
s.ConstructUsing(name => new SampleService());
s.WhenStarted(tc =>
{
XmlConfigurator.ConfigureAndWatch(
new FileInfo(".\\log4net.config"));
tc.Start();
});
s.WhenStopped(tc => tc.Stop());
});
x.RunAsLocalSystem();
x.SetDescription("SampleService Description");
x.SetDisplayName("SampleService");
x.SetServiceName("SampleService");
});
host.Run();
}
}
}
4、配置Log4net和运行我们的服务,服务可以当作控制台来运行,这在开发的时候是非常方便的。服务的安装很方便
SampleWindowsService.exe install
安装成功后,可以通过服务控制台启动,或者也可以通过一下命令运行
SampleWindowsService.exe start
服务的卸载方法也非常简单了
SampleWindowsService.exe uninstall
相关文章:

转载地址:http://oaifz.baihongyu.com/

你可能感兴趣的文章
mysql中的四大运算符种类汇总20多项,用了三天三夜来整理的,还不赶快收藏
查看>>
mysql中的字段如何选择合适的数据类型呢?
查看>>
MySQL中的字符集陷阱:为何避免使用UTF-8
查看>>
mysql中的数据导入与导出
查看>>
MySQL中的时间函数
查看>>
mysql中的约束
查看>>
MySQL中的表是什么?
查看>>
mysql中穿件函数时候delimiter的用法
查看>>
Mysql中索引的分类、增删改查与存储引擎对应关系
查看>>
Mysql中索引的最左前缀原则图文剖析(全)
查看>>
MySql中给视图添加注释怎么添加_默认不支持_可以这样取巧---MySql工作笔记002
查看>>
Mysql中获取所有表名以及表名带时间字符串使用BetweenAnd筛选区间范围
查看>>
Mysql中视图的使用以及常见运算符的使用示例和优先级
查看>>
Mysql中触发器的使用示例
查看>>
Mysql中设置只允许指定ip能连接访问(可视化工具的方式)
查看>>
mysql中还有窗口函数?这是什么东西?
查看>>
mysql中间件
查看>>
MYSQL中频繁的乱码问题终极解决
查看>>
MySQL为Null会导致5个问题,个个致命!
查看>>
MySQL为什么不建议使用delete删除数据?
查看>>