Running Background tasks using IHostedService and BackgroundService (In ASP.NET Core 3.1)

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
hello everyone and welcome to dotnet course central in today's video i'm going to talk about two ways of running background task in asp.net core web application so to show that i'm going to first create asp.net core web application and i'm going to name it as background task dot demo and here i'm going to select api and i'll keep asp.net code 3.1 for running background tasks we don't need any nuget package or anything it is part of the core asp.net infrastructure so first what we'll do is we'll create a new class and i'm going to name the class as background printer and this class will be responsible for printing an incremented number so let's create a number and then we will have a constructor and in the constructor i will just inject the i logger which i'll use to log the output the next thing i'm going to do is i'm going to create a timer here and then finally i'm going to derive from i hosted service and i'll have to implement the interface and the interface has two methods one is the start sync and second one is a stop async so in the start sync we are going to create the timer so we can say timer equal to new timer and then for the callback we can have an inline callback for the time being and here we can just login information printing from worker and then the next parameter is the state which is null for this example and then the due time and for the due time i'm going to use the time span so i can say time span dot 0 which means it'll start immediately and then for the period i'm going to say every five seconds so this is my timer created and then i'm going to say return start completed task and this is the same thing i'm going to do here in the stop sync method so i'm going to say return task dot completed task but here before returning i'm just going to log that the task is getting stopped and then what i'm going to do is because the timer is a disposable i'm going to implement eye disposable and in the dispose method i'm just going to check if prime timer is not null then just dispose the timer and you can see we are getting a suggestion to implement proper dispose pattern and i have a video on eye disposable pattern i'm going to share it video you can see how to do that for the time being i'm just going to keep it this way and then finally we have this number so let's increment the number so here can change the implementation a little bit and here we can say i'm just using interlocked because just to ensure that if there is any multi-threaded call it is not impacted and then i can just print the number so it will print the incremented number every time so this worker is all set the background printer now what i'm going to do is i can go into the program and here directly i can say dot configure services and it takes the service collection so i can say dot add hosted service and for the hosted service i can give the background printer so now the background printer will be added to the di and it will automatically be started now if i run this application let me make it into console and let's run it so you can see this showed up and here the background printer is printing so first it printed number one here then two and three so every five second it is incrementing and printing the number whereas my service is up and running and it's executing on its own so this is how in an asp.net application this is the fast way of implementing a background job now we can change it a little bit just to show how the dependency injection will also work with the background job what i'm going to do is i'm going to abstract the code of this incrementing number and printing into a different class so i can create a new class and i'm going to name it as a worker and here i can have a public void to work and here the implementation might be a little bit different what we can do is we can take a cancellation token and we can say while cancellation token dot is cancelled while it is not cancelled then we can use a logger and here we can say logger dot information and we can have similar number here so and then finally what i can do is i can make it as task and async and here i can do task that delay and i can delay for five seconds again okay so this is this is a worker this is pretty much doing the same thing as this one but without implementing a timer and i can extract the namespace iworker and then in the startup i can configure the worker in the dependency injection container here so i can say services dot at singleton iworker worker and then finally here i can change the whole implementation i can get rid of the number and timer and perform the logger i can take the iworker as another dependency and then i don't have to implement the dispose anymore so i'll just get rid of that by the way when we implement i disposable the dispose method is automatically called by the dotnet framework when the service is going down so here in start sync you can get rid of all this code and i can just call worker dot do work and i'll make it as a sync and everything else remains as is now if i run this application i'm seeing same behavior so this is up and running and now the worker is printing so worker is printing number one number two and then it will subsequently print other numbers so this is one way of implementing background task is through hosted service now the other way is to implement the base class background service so let me create another one and this time let me call it as derived background printer now this class instead of implementing the i hosted service it is going to derive from a class called background service and the background service has a single abstract method that we have to implement which is execute async and here can get rid of this and i'll defile the constructor and just like before i can inject the iworker and here i can call await worker dot to work and passing the cancellation token and make it as i think that's pretty much it so you can see this is much less code compared to the background printer with i hosted service because here we have to handle both start async as well as stop here there is just a single method execute async and now if i run the application but before that i have to change the hosted service configuration here so this will be derived background printer instead of background printer now if i run the application i should see the exact same behavior as before so this is up and running and here we can see the worker printer is printing printed one here two and now three and then so on and so forth so these are the two ways of running background jobs in asp.net core so one is through implementing the interface i hosted service and second one is through deriving from the background services base class as you can see it is pretty straightforward writing a background job and configuring it here with configure services it you can also configure it in startup if you want to configure service at the create host builder level kind of instructs it out at a higher level so that's why i like doing it here but you can as well do it in the startup so to demonstrate that let me just get rid of this code here and in this place we can the services dot add hosted service and we can do the same thing drive printer and run this will also give the exact same result there will be no difference so you can see number one printed starting this is running the number two and then it will continue printing the number as long as the application is up and running let me just undo this and get back to previous implementation where i'm directly configuring it in the program file so these are the main two ways of running background services in asp.net core one is implementing the i hosted service implementing the star testing and stop async method and the second way is deriving from the base abstract class background service and then implementing the abstract method execute sync and as you can see it is tightly connected with the dependency injection container so this can be just for running the class whereas the logic can be implemented in a worker separately so that's all i wanted to cover today if you like this video please give me a thumbs up and if you are not subscribed to my channel and if you think you are getting value out of my channel please subscribe to my channel thanks so much for watching this video
Info
Channel: DotNet Core Central
Views: 46,764
Rating: undefined out of 5
Keywords: BackgroundService, IHostedService, background task, background services, asp.net core background services, asp.net code background tasks, background polling task, asp.net core background possing task, .net core background task, .net core background services
Id: 1Fe7QD7Ovi8
Channel Id: undefined
Length: 12min 6sec (726 seconds)
Published: Mon Jul 27 2020
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.