Explain Background Service in C#

What is Background Service?

a background service is a type of program that runs behind the scenes on a computer or device, performing tasks without needing any interaction from the user.

How to create Background Service?

Step 1. Open Visual Studio, file ->new->project->

New project

Select Console app(.net framework)->click next Give the appropriate name and click on create.

Select Console app

Step 2. Add a Nuget package for your project.

Microsoft.Extensions.Hosting

Step 3. Add a new class to the project and name it “MyBackgroundService.cs”.

MyBackgroundService

Step 4. Inherit the BackgroundService Base class to the MyBackgroundService.cs To implement long-running service i.e IHosted service

And add the below code to it.

This will create a log and it shows a message every five seconds.

Create a log

Step 5. In the Program.cs file, configure services for dependency injection.

Dependency injection

Step 6. Run and Test the background Service.

You can see the running service checking console output by logging messages.

Console output

Step 7. Stop the background service.

You can stop the application by pressing the Ctrl+c’

Background service

Summary

By following this article, we can create background service and run it

I also upload the entire code into Github, click the below link to get it

https://github.com/manideep-bestshop/BackgroundServiceExample