本文共 3555 字,大约阅读时间需要 11 分钟。
Topshelf是一款开源的跨平台宿主服务框架,支持Windows和Mono环境。它使得开发和部署Windows服务变得异常简单,只需几行代码即可构建一个高效便捷的服务宿主。以下将详细介绍如何使用Topshelf创建Windows服务。
Topshelf的代码托管在GitHub上,可以在GitHub Repository下载到最新版本的源码。这里你可以找到最新的开发版本和详细的文档资料。
首先,我们需要创建一个新的控制台应用程序来托管Topshelf服务。在Visual Studio中:
TopShelf.dll和log4net.dll。这两个文件可以从Topshelf的GitHub仓库或NuGet包中获取。接下来,我们需要创建一个服务类,实现启动和停止服务的基本功能。以下是一个简单的示例代码:
using System;using System.Timers;using log4net;namespace SampleWindowsService{ public class SampleService { private Timer _timer = null; private readonly ILog _log = LogManager.GetLogger(typeof(SampleService)); public SampleService() { _timer = new Timer(5000); _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; } }} 在主方法中,我们需要使用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 (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"); } }} 完成上述步骤后,你已经成功配置了一个Topshelf宿主服务。接下来,可以按照以下步骤运行和管理服务:
安装服务:运行以下命令安装服务:
SampleWindowsService.exe install
启动服务:通过以下命令启动服务:
SampleWindowsService.exe start
停止服务:使用以下命令停止服务:
SampleWindowsService.exe stop
卸载服务:如果需要卸载服务,可以运行:
SampleWindowsService.exe uninstall
在配置log4net时,可以通过提供的log4net.config文件定义日志级别和输出格式。例如,配置文件可能包含以下内容:
安装完成后,你可以通过以下命令直接控制服务的运行状态:
SampleWindowsService.exe startSampleWindowsService.exe stopSampleWindowsService.exe restartSampleWindowsService.exe uninstall通过这些简单的命令,你可以轻松地管理和控制你的Windows服务。
如果你需要卸载服务,可以使用以下命令:
SampleWindowsService.exe uninstall
卸载完成后,你可以重新安装服务,重新获取最新版本的服务配置和代码。
通过以上步骤,你已经掌握了使用Topshelf创建和管理Windows服务的基本方法。Topshelf提供了一种简单易用的方式来创建和管理跨平台的服务宿主,减少了传统方式中繁琐的配置和管理流程。希望这篇指南能为你提供实用的参考和帮助。
转载地址:http://oaifz.baihongyu.com/