这是一款很有意思的小工具,可以很快速的创建Windows服务,并且安装运行!
官网: http://topshelf-project.com/
代码托管:https://github.com/topshelf/topshelf
使用方法:http://docs.topshelf-project.com/en/latest/configuration/quickstart.html
某位园友的使用说明:https://www.cnblogs.com/jys509/p/4614975.html
很简单的 Code Case:
using System;
using System.Timers;
using Topshelf;
using log4net;
using log4net.Config;
using System.IO;
namespace Usage
{
public class TownCrier
{
readonly Timer _timer;
readonly ILog log = LogManager.GetLogger(typeof(TownCrier));
public TownCrier()
{
_timer = new Timer(1000) { AutoReset = true };
//_timer.Elapsed += (sender, eventArgs) => Console.WriteLine("It is {0} and all is well", DateTime.Now);
_timer.Elapsed += (sender, eventArgs) => log.Info($"It is {DateTime.Now} and all is well");
}
public void Start() { _timer.Start(); }
public void Stop() { _timer.Stop(); }
}
class Program
{
static void Main(string[] args)
{
var logCfg = new FileInfo(AppDomain.CurrentDomain.BaseDirectory + "log4net.config");
XmlConfigurator.ConfigureAndWatch(logCfg);
var rc = HostFactory.Run(x => //1
{
x.Service<TownCrier>(s => //2
{
s.ConstructUsing(name => new TownCrier()); //3
s.WhenStarted(tc => tc.Start()); //4
s.WhenStopped(tc => tc.Stop()); //5
});
x.RunAsLocalSystem(); //6
x.SetDescription("Sample Topshelf Host"); //服务描述
x.SetDisplayName("Stuff"); //服务显示名称
x.SetServiceName("Stuff"); //服务名称
}); //10
var exitCode = (int)Convert.ChangeType(rc, rc.GetTypeCode()); //11
Environment.ExitCode = exitCode;
}
}
}
安装命令:
Usage.exe Install
Usage.exe Start
Usage.exe Stop
Usage.exe Uninstall