Introduction
In our previous article, we saw the Implementation of a Background Task using BackgroundService with example. If you are new in background task implementation using Background Service class, then please read the below article so you will get a better understanding.
In the above URL, you will get an idea for IHostedService and how it exactly works.
If you want to implement background task using BackgroundService with example see below URL, which I explained in the previous article
In this article, we will see the IHostedService article with an example. For the implementation of a background task, we dont need any Nuget packages or anything, etc. It is in core ASP.NET infrastructure itself. We know a background task can be implemented in two main ways in ASP.NET Core, using BackgroundService Class and IHostedService. IHostedService as Interface.
It defines two methods which are StartAsync(CancellationToken) and StopAsync(CancellationToken). StartAsync is nothing but a trigger when the application host to ready to start the service. It contains the logic to start background tasks. StartAsync is called before the app request processing the pipeline is configured (Startup. Configure) and the server is started and the IApplicationLifetime.ApplicationStarted is triggered.StopAsync is triggered when the application host is performing a graceful shutdown.It contains the logic to end the background task. The IHostedService interface provides a nice way to properly start Background tasks in web applications.
Let's try to understand it by using the below example,
Previously, we saw a particular URL and when it will be Up and when it will be Down. This was maintained in a txt file using BackgroundService Class.We are trying to acheive the same here by using the IHostedService Interface.
Step 1
As you can see in the below diagram, the Worker class is implemented below:
- public class Worker: IWorker
- {
- private readonly ILogger _logger;
- private HttpClient httpClient;
- public Worker(ILogger<Worker> logger)
- {
- this._logger = logger;
- }
Above, we just used a logger in the constructor for logging the output.
- public async Task DoWork(CancellationToken cancellationToken)
- {
- httpClient = new HttpClient();
- while (!cancellationToken.IsCancellationRequested)
- {
- try
- {
- var result = await httpClient.GetAsync("https://www.c-sharpcorner.com/members/atul-warade");
- if (result.IsSuccessStatusCode)
- {
- _logger.LogInformation("The Website is Up.Status Code {StatusCode}", result.StatusCode);
- }
- else
- {
- _logger.LogError("The Website is Down.Status Code {StatusCode}", result.StatusCode);
- }
- }
- catch (Exception ex)
- {
- _logger.LogError("The Website is Down {0}.", ex.Message);
- }
- finally
- {
- await Task.Delay(1000 * 5, cancellationToken);
- }
- }
- }
In the above code, we specify the URL whose status we need to check every 5 seconds.
Step 2
In the below diagram as you can see BackgroundWriter class inherited IHostedService Interface.Also, those two methods which we need to implement StartAsync and StopAsync is also present.In StartAsync, we are calling our main logic method which is DoWork and in the StopAsync method, HttpClient does indirectly implement an IDisposable interface the standard usage of HttpClient is not to dispose of it after every request.Releases unmanaged resources used by the HttpClient and optionally disposes of the managed resources.
- public class BackgroundWriter : IHostedService
- {
- private readonly ILogger<BackgroundWriter> _logger;
- private readonly IWorker _worker;
- private HttpClient httpClient;
- public BackgroundWriter(ILogger<BackgroundWriter> logger, IWorker worker)
- {
- _logger = logger;
- this._worker = worker;
- }
- public async Task StartAsync(CancellationToken cancellationToken)
- {
- await _worker.DoWork(cancellationToken);
- }
-
- public Task StopAsync(CancellationToken cancellationToken)
- {
- httpClient.Dispose();
- return Task.CompletedTask;
- }
- }
Step 3
As you can see below diagram, you need to install Serilog from Nuget for writing texts into a textfile.
There are two packages which you need to install here:
- Serilog.AspNetCore
- Serilog.Sinks.File
Step 4
In the below diagram, you will see I defined the path there where our file was stored. In this file, we will get the status of our URL if it is running or down every 5 seconds.
- public static void Main(string[] args)
- {
- Log.Logger = new LoggerConfiguration()
- .MinimumLevel.Debug()
- .MinimumLevel.Override("Microsoft", LogEventLevel.Warning)
- .Enrich.FromLogContext()
- .WriteTo.File(@"C:\Service\LogFile.txt")
- .CreateLogger();
- try
- {
- Log.Information("Starting up the Service");
- CreateHostBuilder(args).Build().Run();
- return;
- }
- catch (Exception ex)
- {
- Log.Fatal(ex, "There was a problem starting Service");
- return;
- }
- finally
- {
- Log.CloseAndFlush();
- }
-
- }
Step 5
In this below diagram, we need to configure our Interface and Class into Dependency Injection.
- public Startup(IConfiguration configuration)
- {
- Configuration = configuration;
- }
-
- public IConfiguration Configuration { get; }
-
-
- public void ConfigureServices(IServiceCollection services)
- {
- services.AddControllers();
- services.AddSingleton<IWorker, Worker>();
- }
Step 6
This is the last step where you will configure your service with Dependency Injection.
- public static IHostBuilder CreateHostBuilder(string[] args) =>
- Host.CreateDefaultBuilder(args)
- .ConfigureWebHostDefaults(webBuilder =>
- {
- webBuilder.UseStartup<Startup>();
- }).ConfigureServices(service =>
- service.AddHostedService<BackgroundWriter>())
- .UseSerilog();
Now you guys should have a better understanding on Background Task implementation. In this article, we saw an example for IHostedService. Let me know if you have any queries.