Practical Implementation: .NET Core BackgroundServices: Part 2

17 mei 2021 om 10:00 by ParTech Media - Post a comment

In our previous blog titled, Practical Implementation: .NET Core BackgroundServices, we had seen how to implement the background services using a practical implementation. Let's dig a little deeper and understand more about it..

Consider there is a server where an API has been hosted. We want to note down the memory utilization of this server as soon as the API begins. This has to be done until the API is stopped so that we get to know how much memory is being consumed at a particular moment of the day using the data. To implement this, we are going to monitor and save the memory utilization of the server in a file every 15 seconds (it can be configured as per the requirement).

Let's see how to implement this using background services in an API.

In addition to that, to see the implementation of the background services in .Net Core, we are going to learn how to host an API in Internet Information Services (IIS) on the Windows server.

First, open the Run window (Winkey + R) and type ‘inetmgr’. If you are getting the below error, then the IIS needs to be installed.

To install, open the Run window again and type ‘appwiz.cpl’, This will open the Programs and Features installed in your machine.

On that screen, on the left-hand side, there will be an option ‘Turn Windows Features on or off’. Click on that.

On Selecting that option, a popup comes up. Choose the below-highlighted checkboxes and restart the machine after the installation completes.

After restraining, install URL rewrite and .Net Core Runtime & Hosting bundle from the internet.

Link for URL Rewrite - https://www.iis.net/downloads/microsoft/url-rewrite

.Net Core Hosting bundle - https://dotnet.microsoft.com/download/dotnet/3.1

Once all the above-mentioned tools are installed, try opening inetmgr from the run window. A screen like the below should appear.

Now, let's jump in and create an API that can be hosted in IIS.

Create an ASP. Net Core Web Application and provide a valid name to the solution.

Choose the project type as API from the available templates.

The solution explorer would look like the below after creation.

Add a class file to contain the logic for the HostedServices. Provide a valid name to the class and inherit the interface ‘IHostedService’ from Microsoft.Extensions.Hosting.

Implement the required methods (StartAsync, StopAsync). Along with that, implement the logic to write memory utilization to a file in the class file as shown below. This will look for the memory utilized after every 15 seconds and write a file with the data. The filename would be having the DateTime appended to it.

using Microsoft.Extensions.Hosting;

using System;

using System.IO;

using System.Collections.Generic;

using System.Diagnostics;

using System.Linq;

using System.Threading;

using System.Threading.Tasks;



namespace PARTECH_BackgroundServices2

{

  public class PartechHostedService : IHostedService

  {



​    private Timer _timer;

​    public Task StartAsync(CancellationToken cancellationToken)

​    {

​      _timer = new Timer(WriteSystemData, null, 0, 15000);

​      return Task.CompletedTask;

​    }



​    void WriteSystemData(object state)

​    {

​      PerformanceCounter ramCounter;



​      ramCounter = new PerformanceCounter("Memory", "Available MBytes");



​      var data = $"Available Memory - { ramCounter.next() } MB";



   File.WriteAllText($"D:\\PARTECH\\SystemInfo_{DateTime.Now.ToString("MM_dd_yyyy_HH_mm_ss") }.txt", data);

​    }



​    public Task StopAsync(CancellationToken cancellationToken)

​    {

​      //New Timer does not have a stop. 

​      _timer?.Change(Timeout.Infinite, 0);

​      return Task.CompletedTask;

​    }



  }

}


Inject the hosted service class file in the configureServices method present in the Startup.cs file. Now, you can run the solution and check if the required data is being received in the provided path.

services.AddHostedService<PartechHostedService>();

After this, publish the project to the path from which the website would be created. To publish, choose the folder target option.

Now, go to IIS, Right-click on the ‘Sites’ in the left pane, select ‘Add Website’ and provide options as shown in the below image.

Here, Sitename is the name of the website that would be stored in the IIS. The next field is the Application Pool. As the name suggests, it indicates the application pool in which the application is running. We can individually configure elements at the application pool level.

Next is the path of the code where the background service has been published. Click on ‘Test settings’. If you see there is no authorization to access the path, click on ‘Connect as’.Provide the credentials of the server through which it has been logged in.

Next provide the binding type as HTTPS. From the dropdown, select the IP that is available and provide a valid port number. And in case of masked IP, a hostname can also be provided through which the application can be accessed from the browser.

Since the HTTPS option has been selected, choose a valid certificate and finally click on the OK button. This will create a website of the provided name under Sites and it will be accessible by the provided IP and masked URL.

Now, enable directory browsing for the site. And try to hit the API from the browser to validate if it is working. Here the URL is https://192.168.0.18/weatherforecast. Do you see the result on the browser page?

Now, open the file explorer and navigate to the folder path which has been configured to write the utilization data. You will see files getting created every fifteen seconds.

Conclusion

This is one another simple and practical example that shows how to use background services and host them on a Windows server. Like this, many other background schedules can be processed through this code.

Nieuwste