前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >使用Topshelf 5步创建Windows 服务

使用Topshelf 5步创建Windows 服务

作者头像
张善友
发布2018-01-19 16:43:54
1.2K0
发布2018-01-19 16:43:54
举报
文章被收录于专栏:张善友的专栏张善友的专栏

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

1、Topshelf的代码托管在http://topshelf-project.com/,可以在这里下载到最新的代码。

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

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

代码语言:js
复制
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如何设置我们的服务的配置和启动和停止的时候的方法调用。

代码语言:js
复制
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

相关文章:

使用Topshelf创建Windows 服务

A WCF calculator in a windows service with TopShelf

WCF service with Topshelf using as a host, log4net as logging tool, and HTML as output

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2011-05-04 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
相关产品与服务
代码托管
CODING 代码托管(CODING Code Repositories,CODING-CR)是为开发者打造的云端便捷代码管理工具,旨在为更多的开发者带去便捷、高效的开发体验,全面支持 Git/SVN 代码托管,包括代码评审、分支管理、超大仓库等功能。
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档