使用Topshelf 5步建立Windows 服务

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

一、Topshelf的代码托管在http://topshelf-project.com/,能够在这里下载到最新的代码。windows

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

三、建立一个简单的服务类,里面包含两个方法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;
}
}
}
四、在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();
}
}
}
四、配置Log4net和运行咱们的服务,服务能够看成控制台来运行,这在开发的时候是很是方便的。服务的安装很方便
SampleWindowsService.exe install
安装成功后,能够经过服务控制台启动,或者也能够经过一下命令运行
SampleWindowsService.exe start
服务的卸载方法也很是简单了
SampleWindowsService.exe uninstall
相关文章
相关标签/搜索