关于TopShelf 描述:
Topshelf is a framework for hosting services written using the .NET framework. The creation of services is simplified, allowing developers to create a simple console application that can be installed as a service using Topshelf. The reason for this is simple: It is far easier to debug a console application than a service. And once the application is tested and ready for production, Topshelf makes it easy to install the application as a service.
1、ok,首先使用VS 建立一个控制台 程序,使用Nuget 搜索 TopShelf 引用 TopShelf 和 TopShelf.Log4Net
2、写入代码:
public class TownCrier
{
readonly Timer _timer;
public TownCrier()
{
_timer = new Timer() {AutoReset = true};
_timer.Elapsed += (sender, eventArgs) => Console.WriteLine("It is {0} an all is well", DateTime.Now);
}
public void Start() { _timer.Start(); }
public void Stop() { _timer.Stop(); }
} public class Program
{
public static void Main()
{
HostFactory.Run(x =>
{
x.Service<TownCrier>(s =>
{
s.ConstructUsing(name=> new TownCrier());
s.WhenStarted(tc => tc.Start()); //指定此服务的启动函数
s.WhenStopped(tc => tc.Stop()); //指定此服务的终止函数
});
x.RunAsLocalSystem(); x.SetDescription("这是一个测试的服务 作用就是控制台输出~~"); // 服务描述
x.SetDisplayName("_Rufus_Test_Winservices"); //服务显示名字
x.SetServiceName("_Rufus_Test_winServices"); //服务名字
});
}
}
3、编译
4、找到你编译成功的exe程序 执行cmd命令 (ps: 需要管理员权限)
XXXXX install (xxxx是你编译的程序名 例如 我的为 WinServerTest install)
5、现在 查看 服务管理器 发现 _Rufus_Test_Winservices 已经注册到 里面 了,手动启动这个 服务即可。