Background Tasks Are Finally Fixed in .NET 8

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
hello everybody I'm Nick and in this video I'm going to show you how finally in.net 8 Microsoft fixes or completes the concept of a background task also known as a background service or the hosted service now if you don't know what a hosted service is or a background Services I do have a video on it I will explain however what it is in this video but in this video we're going to focus into what is coming in.net 8 which I and many people I worked with were really missing if you want to do any simple or even complicated background processing in your dotted application then that concept is for you if you like my content and you want to see more make you subscribe for more training check out my courses on domtrain.com now before I move on I'd like to let you know we just launched a brand new course on Dom train called getting started with solution architecture and that course is made by James estam like I have said in the past I only want to make courses myself on topics I am an absolute expert on and on this I just I'm not as good as James so I asked him to come over and offer that course for us James is a senior solution architect for awus so his knowledge on the subject and his position in the biggest cloud provider in the world makes him the perfect educator for something like this the course is fantastic I've taken it myself and I cannot stress enough how good the quality of that course is I have said it in the past and I will say it again getting very good in solution architecture and understanding the subject will really Elevate you as a software engineer more than becoming better at the code itself because after some point you're gonna Plateau but solution architecture doesn't really have a limit and the moment you understand when to choose the right and for the right job you're going to be way more valuable into your company and your team Now to celebrate the launch I want to offer the first 400 of you a 15 discount code so you can use the code you see now on your screen and claiming 15 discount at checkout trust me this go really really fast so if you want to get the course get it sooner than later now back to the video alright I'm sure to have here I have a simple.net 8 API but it doesn't really have anything it is just a web application and I'm going to use it as a skeleton to show you what was added and really what the hosted service is so up until.net7 we really had two ways of doing background stuff in our dotnet application whether that's an API or just a normal dotnet app and that is by using either a hosted service or a background service now a background service is pretty self-explanatory so I'm gonna say example BG service over here and I'm going to extend the background service class and if I do that and I implement the one method in here I have this execute async method which I can turn into an async task and then I can do anything I want here and what most people do with this is that they say while the cancellation token is not cancellation requested so basically while the application is still running then do something and also maybe I'll wait for some delay and so on so if I wanted to have something very simple here I could just do console.writeline ping and I'm going to sort the modifiers and in order for this to actually be picked up by.net and used I have to go into the program.cs and I have to say builder.services.ad hosted service and I'm gonna say example BG service and now if I go ahead and I just run this application then what you're going to see is the application would start and after it starts I'm going to get a ping every second very self-explanatory and this will just keep working in the background now of course if I was not awaiting anything and if I was not in a loop and I just did that then what you might expect will happen you're only gonna see one ping and then we're out of that method and so on so nothing really happens in the background it will just run as the application is starting and that is it so that is the background service which I think is the most used one as well but we also have another thing we have an example cervix over here and this will implement the I hosted service and that actually has two methods the start async and they stoppacing as the name implies one will be triggered on the start of the application and one will be triggered at the well stopping of the application so if I turn this into async methods then I can put any code I want here I'm going to actually inject a private read-only I logger of that type and I'm going to use that to just print something into the console so I'm going to say for example log information and then start a Sync here and then log information stop async so if I just leave it as it is and I go ahead and I register it in my program.cs then exactly what you think might happen will happen so in the beginning of the application I'm going to get the start I think before the whole application actually starts so first that thing will be triggered and then I'm going to have the application running and when I say stop the application then the stop I think will be triggered and the application will exit and that is great that's fine you can have something that starts then does something in there after it starts and then it stops however we have a bit of an issue here let's say you have some sort of asynchronous work you want to do during start or stop let's say that this session going to work takes some time now ideally you don't want to have something that does take a lot of time in these type of situations you're gonna see why but let's see if something does really take some time and I'm gonna say await.task.delay and I'm gonna have 20 seconds here so let's add that watch what happens if I just say run then we're going to stay here for a solid 20 seconds looking at this because the start method of each individual hosted service by the way will be a weighted synchronously it's not synchronous it's still awaited asynchronously but it has to finish the whole awaiting process has to finish before we move on into running the application and for many people that's problematic because well you might not need that thing to actually start during that time immediately you could just afford for that to start in 30 seconds and so on but you still want your application to immediately start so if you didn't really have an option what I've simply do is they were wrapping things into tasks and taskbot runs and so on and that is easy to mess up as well so that is one of the things that we're finally getting fixed in.net 8. now the way this is fixed is actually very simple now in the service configuration I can say builder.services.configure and I can configure the host options which by the way you can configure for other things in the dotnet application for example if I just show you some options you have things like shutdown timeouts or startup timeouts if the application is taking a long time to start or stop then you can configure a timeout and this will just kill it or you can have things like background service exceptional Behavior so if you have an exception there then how will your application react do we just kill it do we do something else in fact if I show you the options you're gonna get the ignore and you're gonna get the stop host so those are a few options you might have here but you also have two new ones now which is a services start concurrently and services stop concurrently by default those are false but I can now go ahead and I can set those to true so if I do that even if I have first many services but many services that do some longer waiting on the start method over here like 20 seconds I no longer have to wait in fact I'm going to just move this start async below and turn this into 10 seconds just to showcase the point and then I'm going to say run are you going to see the application will start immediately and that task has now started in the background concurrently and every other task I have will also start concurrently because they're now wrapped in a special task.run approach that doesn't block the application from starting or stopping for that matter so that is one of the things we didn't have and now we have in dot at 8. now what is the other one well the other one is that if we go back to this hosted service you don't really have much control in what happens it's not really granular control into what happens you have start I think which is triggered when the application is starting and a stop testing which is triggered when the application is stopping but what if you want more control well if you want more control in dotnet 8 with a brand new I hosted lifecycle service and with that interface we don't only have the start icing and stop async but we also have the started async when something has started the starting async when something is in the process of starting they stopped async and they're stopping async so we're going to go ahead and Implement those and I'm going to just quickly print in the console just the name of each method so you can see exactly what is going on I'm going to say return task dot completed task over here and I'm just very quickly going to implement all of them of camera so you don't have to see me do the same thing 15 times so just to recap now we have start stop started start thing stopped and stopping and nothing changes on the registration front so this is still an ad hostage service call so all I want to do now now just say run and watch what happens first we have the start thing async so the application is in the process of starting then we have the call to the start async so now it will start then you have the started so everything about it has completed and when I press the stop button you're going to see the stop ping stop and stop so that is the order ing starting stop or start and then stopped or started and it's gonna be a bit confusing because you could assume a different order but the way I think of it is ing nothing and then Ed and that's how I rationalize the flow and if you work with middleware in the past in MVC you would know that they use the sort of the same naming approach for health filters and middleware is executed the start instruction currently stuff are very important in my opinion because you sort of had to compromise before and try to hack your way around doing the exact same thing but using a background service that you didn't necessarily need so now you no longer need that and more granular control over here with each individual method also gives you more power to do more fancy things with different levels of the application startup process but now I want to know from you have you you use background Services before or hosted services like that and have you encountered that issue because that I hosted service blocking thing I've encountered so many times in the past and I just did not understand why it was happening so leave a comment down below and let me know well that's all I have for you for this video thank you very much for watching and as always keep coding
Info
Channel: Nick Chapsas
Views: 56,634
Rating: undefined out of 5
Keywords: Elfocrash, elfo, coding, .netcore, dot net, core, C#, how to code, tutorial, development, software engineering, microsoft, microsoft mvp, .net core, nick chapsas, chapsas, dotnet, .net, background service, background service .net 8, hangfire, hosted service, hosted service c#, background service c#, background services in .NET 8
Id: XA_3CZmD9y0
Channel Id: undefined
Length: 10min 28sec (628 seconds)
Published: Mon Aug 21 2023
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.