C # to create a Windows service using Topshelf

The purpose of this writing is to record one of the easiest ways to develop Windows services - Topshelf. Dependencies downloaded before use: Topshelf.dll  Topshelf.4.2.0.zip  either directly by mounting Nuget: Install-Package Topshelf

Topshelf document Address:  https://topshelf.readthedocs.io/en/latest/configuration/quickstart.html

Directly on the code

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

Installation Services command-line installation to note here: You must use an administrator run a command line window! !

Command line window will be involved (in server.exe procedure of example, self-replacement):

Installation Services server.exe install

Start Service server.exe start

Stop service server.exe stop

Uninstall the service server.exe uninstall


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

Guess you like

Origin www.cnblogs.com/su-king/p/11389444.html