Tuesday, 6 June 2023

HostedService in Microsoft.NET Core

Leave a Comment

In the. A NETCore HostedService class represents an asynchronously operating background task or service within an application. Its function is to begin when the application begins and end when the application ends. HostedService is an integral part of the generic host in.NET Core, facilitating various functionalities such as background process execution, job schedule management, and system resource monitoring.


The resources utilised for this tutorial are listed below.

  1. VS 2022 Community Edition (64-bit)
  2. .Net 7.0
  3. Console App

Here's an example of creating a HostedService in .NET Core.

using System;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;

public class MyHostedService : IHostedService, IDisposable
{
    private readonly ILogger<MyHostedService> _logger;
    private Timer _timer;

    public MyHostedService(ILogger<MyHostedService> logger)
    {
        _logger = logger;
    }

    public Task StartAsync(CancellationToken cancellationToken)
    {
        _logger.LogInformation("MyHostedService is starting.");

        _timer = new Timer(DoWork, null, TimeSpan.Zero, TimeSpan.FromSeconds(5));

        return Task.CompletedTask;
    }

    private void DoWork(object state)
    {
        _logger.LogInformation("Doing some work...");
        // Perform your background processing or task here
    }

    public Task StopAsync(CancellationToken cancellationToken)
    {
        _logger.LogInformation("MyHostedService is stopping.");

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

        return Task.CompletedTask;
    }

    public void Dispose()
    {
        _timer?.Dispose();
    }
}
The StartAsync and StopAsync methods must be implemented because the class MyHostedService conforms to the IHostedService interface, which is the case here. The ILogger interface is injected into the service's constructor for monitoring purposes.

During application initialization, the StartAsync method is invoked. This method can be used to initialise and initiate any background duties or processing. In this example, a Timer is created to simulate a task that repeats every 5 seconds.

The StopAsync method is invoked when an application is terminated. Its purpose is to gracefully halt any ongoing task and clean up any resources. In the example provided, the Timer is halted.

The Dispose method is implemented in order to appropriately release all service-utilized resources.

To utilise the MyHostedService, it must be registered within the application's dependency injection container. Here is an example of configuring and executing the HostedService within a console application.

using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;

var host = new HostBuilder()
.ConfigureServices((hostContext, services) =>
{
    services.AddHostedService<MyHostedService>();
})
.ConfigureLogging(logging =>
{
    logging.ClearProviders();
    logging.AddConsole();
})
.Build();

await host.RunAsync();
In this scenario, the AddHostedService method is used to register MyHostedService within the dependency injection container as a hosted service.

When the console application is executed, MyHostedService will launch and run in the background until the application is terminated.

Conclusion

Please note that the Microsoft.Extensions.Hosting and Microsoft.Extensions.Logging namespaces, which are commonly used in.NET Core applications, are required for this example. Ensure that your project contains the required NuGet packages (Microsoft.Extensions.Hosting and Microsoft.Extensions.Logging.Console).

This example demonstrates the fundamentals of a HostedService in.NET Core. It is modifiable and expandable to suit your particular needs.

Best ASP.NET 7.0.3 Hosting Recommendation

One of the most important things when choosing a good ASP.NET Core 7.0.3 hosting is the feature and reliability. HostForLIFE is the leading provider of Windows hosting and affordable ASP.NET Core 7.0.3, their servers are optimized for PHP web applications. The performance and the uptime of the hosting service are excellent and the features of the web hosting plan are even greater than what many hosting providers ask you to pay for. 

At HostForLIFEASP.NET, customers can also experience fast ASP.NET Core 7.0.3 hosting. The company invested a lot of money to ensure the best and fastest performance of the datacenters, servers, network and other facilities. Its datacenters are equipped with the top equipments like cooling system, fire detection, high speed Internet connection, and so on. That is why HostForLIFEASP.NET guarantees 99.9% uptime for ASP.NET Core 7.0.3. And the engineers do regular maintenance and monitoring works to assure its Orchard hosting are security and always up.

0 comments:

Post a Comment