博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Windows 服务开发框架介绍 - Topshelf
阅读量:4562 次
发布时间:2019-06-08

本文共 2131 字,大约阅读时间需要 7 分钟。

关于 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.

 

示例

第一步:新建一个 C# 控制台应用程序。

第二步:用 Nuget 引用 TopShelf 和 Log4net。

第三步:贴出下面的代码。

using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks;using System.Timers;using Topshelf;using Topshelf.Builders;using Topshelf.Configurators;using Topshelf.HostConfigurators;namespace TopshelfStudy{    public sealed class TimeReporter    {        private readonly Timer _timer;        public TimeReporter()        {            _timer = new Timer(1000) { AutoReset = true };            _timer.Elapsed += (sender, eventArgs) => Console.WriteLine("当前时间:{0}", DateTime.Now);        }        public void Start() { _timer.Start(); }        public void Stop() { _timer.Stop(); }    }    class Program    {        static void Main(string[] args)        {            HostFactory.Run(x =>            {                x.Service
(s => { s.ConstructUsing(settings => new TimeReporter()); s.WhenStarted(tr => tr.Start()); s.WhenStopped(tr => tr.Stop()); }); x.RunAsLocalSystem(); x.SetDescription("定时报告时间"); x.SetDisplayName("时间报告器"); x.SetServiceName("TimeReporter"); }); } }}

第四步:编译、Release 生成。把 Release 文件夹 Copy 到 C 盘。

第五步:以管理员身份运行 cmd,安装、启动。

SampleWindowsService.exe install

启动

SampleWindowsService.exe start

如果要卸载也很方便

SampleWindowsService.exe uninstall

效果如下:

 

最后 Windows Service 没有 Console.WriteLine,我们可以把输出信息输出到文件。

StreamWriter sw = new StreamWriter("e:\\temp\\log.log");sw.AutoFlush = true;Console.SetOut(sw);

参考网站:

谢谢浏览!

转载于:https://www.cnblogs.com/Music/p/topshelf-1.html

你可能感兴趣的文章
一道面试题及扩展
查看>>
Unity 3D 我来了
查看>>
setup elk with docker-compose
查看>>
C++ GUI Qt4学习笔记03
查看>>
Java基础回顾 —反射机制
查看>>
c# 前台js 调用后台代码
查看>>
2017-02-20 可编辑div中如何在光标位置添加内容
查看>>
$.ajax()方法详解
查看>>
day42
查看>>
jquery操作select(增加,删除,清空)
查看>>
Sublimetext3安装Emmet插件步骤
查看>>
MySQL配置参数
查看>>
全面理解Java内存模型
查看>>
A - Mike and palindrome
查看>>
DOTween教程
查看>>
java web中java和python混合使用
查看>>
创建学员类和教员类
查看>>
Cookie和Session的作用和工作原理
查看>>
字符串操作
查看>>
Visual Studio中改变environment 的布局和显示风格
查看>>