Topshelf 建立.net服務整理和安裝步驟

龐順龍發表於2019-05-11

Topshelf 建立.net服務整理和安裝步驟

windowsService和topshelf服務區別請看 → windowsSevice程式和topshelf程式建立服務對比

Topshelf下載地址https://github.com/Topshelf/Topshelf/downloads

官網http://topshelf-project.com/

文件http://docs.topshelf-project.com/en/latest/

1、建立專案


2、新增Topshelf,使用nuget安裝最新的topshelf程式包


3、編寫測試程式碼,直接貼Program類程式碼

using System.Timers;
using Topshelf;

namespace TopShelfConsoleApplication
{
    public class TownCrier
    {
        TopshelfClass topshelfClass = new TopshelfClass();
        readonly Timer _timer;
        public TownCrier()
        {
            //設定了一個 1000 毫秒的服務執行間隔   
            _timer = new Timer(1000) { AutoReset = true };
            _timer.Elapsed += new ElapsedEventHandler(topshelfClass.Test);
        }
        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("Topshlef服務描述......");
                x.SetDisplayName("TopshlefTest");
                x.SetServiceName("TopshlefTest");
            });
        }
    }
}

TopshelfClass處理類

using System;
using System.IO;
using System.Timers;

namespace TopShelfConsoleApplication
{
    public class TopshelfClass
    {
        public void Test(object source, ElapsedEventArgs e)
        { 
            string path = "F:\\TopshelfTest\\TopshelfTest.txt";
            FileStream fs = new FileStream(path, FileMode.Append);
            StreamWriter sw = new StreamWriter(fs);
            sw.WriteLine(DateTime.Now.ToString());
            sw.Close();
            fs.Close(); 
        }
    }
}

具體說明請參照官網給的技術解釋文件,我就不在這裡解釋程式碼咯:https://topshelf.readthedocs.org/en/latest/configuration/quickstart.html

我只說明一點:上面程式碼設定為1秒執行一次,在txt檔案追加下時間戳,為了防止本地開發測試的除錯問題,可以設定屬性:


4、釋出部署

a、釋出部署包,自行處理

b、進入cmd命令,進入部署包目錄,找到exe檔案執行install安裝命令,如下圖:


c、檢視本機服務,可見已經安裝成功:


d、安裝n個相同服務使用命令:-instance " test1" install



e、常用命令


install:ConsoleApplication1.exe install 
start:ConsoleApplication1.exe start ,執行後服務被啟動
stop:ConsoleApplication1.exe stop ,執行後服務被停止
uninstall:ConsoleApplication1.exe uninstall,執行後服務被解除安裝
-instance:  ConsoleApplication1.exe -instance " test1" install
5、測試服務執行,開啟兩個服務,結果如下:



至此,簡單的topshelf服務使用就完成咯~~~~~

請喊我大龍哥最後編輯於:3年前

內容均為作者獨立觀點,不代表八零IT人立場,如涉及侵權,請及時告知。

相關文章