1. 程式人生 > >一款非常好用的 Windows 服務開發框架,開源專案Topshelf

一款非常好用的 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、然後嘗試執行程式碼,結果如下: