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.


Join the conversation! Your thoughts help the community grow.