• 一款非常好用的 Windows 服务开发框架,开源项目Topshelf


      Topshelf是一个开发windows服务的比较好的框架之一,以下演示如何开发Topshelf服务。

    1、首先打开你的vs。新建一个TopshelfStudy控制台程序,如下图所示:

    这是我用vs2017新建的。

    2、然后选中你的项目,运行Nuget,可以手工搜索Topshelf进行安装,也可以通过程序包管理器控制台进行安装,Install-Package Topshelf,具体操作如下。

    因为我选择的安装版本支持的比较高,这里为了不出问题。把项目的目标框架设置为.NET FrameWork 4.6 。低版本的不支持

    3、安装成功之后会有如下引用。

    4、接下来创建TimeReporter.cs类。

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    using System.Timers;
    
    namespace TopshelfStudy
    {
        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(); }
        }
    }

     5、Program.cs代码如下

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    using Topshelf;
    
    namespace TopshelfStudy
    {
        class Program
        {
            static void Main(string[] args)
            {
                HostFactory.Run(x =>
                {
                    x.Service<TimeReporter>(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");
                });
            }
        }
    }

    6、然后尝试运行代码,结果如下:

    人生,总是有一些空城旧事,年华未央;总是有些季节,一季花凉,满地忧伤。许多事,看开了,便会峰回路转;许多梦,看淡了,便会云开日出。学会思索,学会珍藏,微笑领悟,默默坚强。
  • 相关阅读:
    装饰器和表达生成式
    函数
    字符编码
    函数基础
    列表,字典与集合
    Linux Semaphore
    tp5安装easyWeChat
    wx.request
    小程序设计规范
    小程序的概念和特点
  • 原文地址:https://www.cnblogs.com/yuzhou133/p/10223319.html
Copyright © 2020-2023  润新知