C# 使用 Topshelf 建立Windows服務

本文寫做的目的是,記錄一種最簡單開發 Windows 服務的方式– Topshelf 。使用前先下載依賴文件: Topshelf.dll Topshelf.4.2.0.zip 或者直接經過 Nuget 安裝:Install-Package Topshelfhtml

Topshelf 文檔地址: https://topshelf.readthedocs.io/en/latest/configuration/quickstart.htmlapp

直接上代碼ui

public class TownCrier
{
    readonly Timer _timer;
    public TownCrier()
    {
        _timer = new Timer(1000) {AutoReset = true};
        _timer.Elapsed += (sender, eventArgs) => Console.WriteLine("It is {0} and all is well", DateTime.Now);
    }
    public void Start() { _timer.Start(); }
    public void Stop() { _timer.Stop(); }
}

public class Program
{
    public static void Main()
    {
        var rc = HostFactory.Run(x =>                                   //1
        {
            x.Service<TownCrier>(s =>                                   //2
            {
               s.ConstructUsing(name=> new TownCrier());                //3
               s.WhenStarted(tc => tc.Start());                         //4
               s.WhenStopped(tc => tc.Stop());                          //5
            });
            x.RunAsLocalSystem();                                       //6

            x.SetDescription("Sample Topshelf Host");                   //7
            x.SetDisplayName("Stuff");                                  //8
            x.SetServiceName("Stuff");                                  //9
        });                                                             //10

        var exitCode = (int) Convert.ChangeType(rc, rc.GetTypeCode());  //11
        Environment.ExitCode = exitCode;
    }
}

安裝服務 命令行安裝  這裏要注意:必須使用管理員方式運行命令行窗口!!spa

命令行窗口中會涉及到的命令(以程序 server.exe 舉例,自行替換):命令行

安裝服務 server.exe installcode

啓動服務 server.exe startserver

中止服務 server.exe stophtm

卸載服務 server.exe uninstallblog


參考文章 ip

http://www.javashuo.com/article/p-ujsqgtck-ne.html

https://www.jianshu.com/p/56dc3ca16528

相關文章
相關標籤/搜索