This article was first published in: code friends network – a focus. NET/.NET Core development programming enthusiast community.

The article directories

C#/.NET create Windows service based on Topshelf

  1. Creating Windows Service programs and installing and uninstalling Services based on Topshelf (1)
  2. Create an application daemon (service) based on Topshelf in C#/.NET application development (2)
  3. Analysis and solution of the problem that the client desktop program started as a service does not display UI interface (3)

preface

Windows Services should be familiar to anyone using the Windows operating system. On Windows, we can run service. MSC in the Run window:

You can open a window to view Windows services, as shown in the figure below:

Windows services are basically service processes running in the background without a UI. Each service handles its own task and has a specific start or stop policy. As a result, Windows services are often used to handle scheduled tasks or scheduling.

So, is it possible for.net developers to create Windows services themselves, and how to create Windows services using C#?

This article will share with you a Windows service created based on Topshelf.

Create Topshelf service items

First, open Visual Studio(Visual Studio 2019 is used for this article), open the New project dialog box, and select. NET Framework Console App(.NET Framework), as shown below:

Note: Only console applications can be selected

Click “Next”, enter TopshelfDemoService in the project name, select 4.6.2 for.NET Framework, fill in the options as you like, and click “Create”.

Install Topshelf components

In the TopshelfDemoService project, open the Nuget package management tool and search Topshelf. Select Topshelf in the search result and click “Install”, as shown in the picture:

Write sample program code for Topshelf service

With the Topshelf component installed, we can start writing sample code for the service.

First, create a class called HealthMonitorService.cs (whose purpose is assumed to periodically monitor the health of a system) and create methods in it: Start() and Stop() and a timer that periodically executes the task of checking the health of the system (here the simulated output is one text message per second to the console). The complete code is as follows:

using System;
using System.Timers;

namespace TopshelfDemoService
{
    internal class HealthMonitorService
    {
        private readonly Timer _timer;
        public HealthMonitorService()
        {
            _timer = new Timer(1000) { AutoReset = true };
            _timer.Elapsed += (sender, eventArgs) => Console.WriteLine("Perform the system health check. All indicators are normal. Execution time: {0}", DateTime.Now);
        }

        public void Start()
        {
            _timer.Start();
        }
        public void Stop() { _timer.Stop(); }}}Copy the code

Then create a service configuration class named MyServiceconfigure. cs, which is used to configure various running parameters of the Topshelf service. The code is as follows:

using System;
using Topshelf;

namespace TopshelfDemoService
{
    internal class MyServiceConfigure
    {
        internal static void Configure()
        {
            var rc = HostFactory.Run(host =>                                    // 1
            {
                host.Service<HealthMonitorService>(service =>                   // 2
                {
                    service.ConstructUsing(() => new HealthMonitorService());   // 3
                    service.WhenStarted(s => s.Start());                        // 4
                    service.WhenStopped(s => s.Stop());                         // 5
                });

                host.RunAsLocalSystem();                                        // 6

                host.EnableServiceRecovery(service =>                           // 7
                {
                    service.RestartService(3);                                  // 8
                });
                host.SetDescription("Windows service based on topshelf");       // 9
                host.SetDisplayName("Topshelf demo service");                   // 10
                host.SetServiceName("TopshelfDemoService");                     // 11
                host.StartAutomaticallyDelayed();                               // 12
            });

            var exitCode = (int)Convert.ChangeType(rc, rc.GetTypeCode());       // 13
            Environment.ExitCode = exitCode; }}}Copy the code

Note: The meanings of the numbers are explained at the end of this article.

Finally, open the program. cs file and start the Topshelf service as follows:

namespace TopshelfDemoService { class Program { static void Main(string[] args) { MyServiceConfigure.Configure(); }}}Copy the code

Now that you’re done, the entire sample program is ready. Press F5 to run the sample program and you should see console information similar to the following:

As you can see, the TopshelfDemoService we created prints one text message per second to the console, as we expected.

In this way, we have successfully created a Windows service based on Topshelf. Of course, this is only a simple and sample service application, without complex business logic, configuration, etc. It’s all there for you to discover.

Install and uninstall as a Windows service

We just ran a console application, and if we close the console application, the scheduled task will also be stopped. If we want scheduled tasks to run all the time, we need to install the console application as a service into the Windows server process. How do we do this?

Very simple install and uninstall commands.

First, open a command-line tool as an administrator and go to the directory where the console application resides.

The installation

Run the following command to install the service:

TopshelfDemoService.exe install
Copy the code

Open the Windows Service view window (refresh), and you can see that Topshelf Demo Service is in the service list, as shown in the following figure:

At this point, we just need to follow the Windows service to operate the service.

uninstall

To uninstall the service, run the following command:

TopshelfDemoService.exe uninstall
Copy the code

Topshelf Configuration parameters

1. Set the service host to use hostfactory.run () to create and Run a Topshelft service. 2. Set the Topshelf usage type HealthMonitorService as the service class. 3. Configure how to create an instance of the service, using the keyword new to instantiate a HealthMonitorService object. You can also use IoCp containers to instantiate the service object. 4. Set the operation to be performed when the service starts. 5. Set the operation to be performed when the service stops. 6. Set the service to run as the local system. 7. Enable the service recovery mode (automatic recovery when the service stops unexpectedly). 8. Set the delay for the first automatic service recovery to 3 minutes. 9. Set the description of the Topshelf service in Windows. 10. Set the Topshelf service name in Windows. 11. Set the Topshelf service name in Windows. 12. Set the Topshelf service to automatically run (delay) when Windows starts. 13. Set the service exit code.

Sample code hosted and downloaded

The host address of this sample code can be found in the original source: sample code download address