Background Jobs and .NET Hosted Services 
Tags: csharp, dotnet, programming, tutorial
Published: 2021-10-16 20:50:45

# Introduction :
* Background jobs are an alternative to synchronous processing, it's an approach to lighten the main thread and offload tasks to a secondary thread. 


* To explain the concept let's imagine a web application dedicated to video processing which's obviously a heavy task, so the main application get the request from a third party application or the browser, then it delegates the task to a background job, but the main thread can't wait for the response cause it will take a considerable amount of time to finish the task from the worker job, so to free the main application thread the communication is established asynchronously by creating a message queue bridge between the application and background job, so the main application place the task in queue and then move on to get more processing request, and the background job can treat the requests at it's own speed. 


* The main criteria to decide whether a task can be executed in background or not is by asking yourself if the task need the interaction with user while in execution or the user is obliged to wait for the job result, if the answer is yes so the backgound job implementation can be inapropriate in this case. 

# Background jobs triggers types : 
* There's two type of background job triggers : 

	 * **Event driven trigger :**  the background job is launched in parallel with the main application when a start event is raised. 
	 * **Schedule driven trigger :** in this approach the task is invoked periodically based on a timer.

# Dotnet Core Hosted Services : 
* In the .Net core platform we can build background jobs by implementing **IHostedService** interface. 

![IHostedServiceInterface](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/6en54ouh5ak2dveujahu.PNG)

* In the code above The **StartAsync** method is triggered when our service kicks off, it's a setup method where we configure and launch the background job to do the work. 

* On the other side **StopAsync** is called when we stop our background service so we can do whatever we need to dispose used resources.

> The .Net hosted services are tied to the hosted service, that means
> they are deployed with the main application within the same host
> infrastructure.

# Dotnet hosted service example :

* We will create a simple hosted service which will simply print Hello World every 10 seconds, and inject it as hosted service to  ASP .Net Api application.

	 **1.  Implemente IHostedService**
 
![Hosted service](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/bannsnr9413xflvkkdlw.PNG)

 * In the code above we decalred an instance of a Timer object which will be configured to execute a callback method periodically.

> The [Timer](https://docs.microsoft.com/en-us/dotnet/api/system.timers.timer?view=net-5.0) is an object  that raises an event after a number of milliseconds elapsed. You can configure the Timer object to raise the event just once or repeatedly. 


* In the StartAsync method we configured the timer to execute  `PrintHelloWord()` periodically after each 10 seconds, in the other side StopAsync method is used  to stop the timer callbacks when the job is turned off.

 **2. Configure API by adding our hosted service**
 
* We need to add our hosted service to `ConfigureServices` method in startup.cs :

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/8aikrnh7pt2jqnymnr1n.PNG)

* And we are done if we start our api now MyHostedService will kicks off, check the Debug output to see the result :wink:.

# Hosted services limitation :

* The hosted services are tied to the main host web application, so when we scale horizontally our web application it involves the creation of new job instance. So we should be aware of that and avoid using hosted services in cases where jobs will compete with each others and lead to unwanted behaviours.