一款非常好用的 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、然后尝试运行代码,结果如下:

猜你喜欢

转载自www.cnblogs.com/yuzhou133/p/10223319.html