C# 使用 Topshelf 創建Windows服務


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

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

直接上代碼

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;
    }
}

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

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

安裝服務 server.exe install

啟動服務 server.exe start

停止服務 server.exe stop

卸載服務 server.exe uninstall


參考文章 

https://www.cnblogs.com/mushroom/p/4952461.html

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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM