BACKGROUND TASKS in ASP NET Core | Getting Started With ASP.NET Core Series
HTML-код
- Опубликовано: 27 авг 2024
- Hello, Background tasks are those that run in the background without interfering with the primary process. In ASP NET Core background tasks are implemented as Hosted Services. This allows us to perform tasks outside of the main web thread, determine changes to data in a database, and also long-running tasks to process messages from the queue, etc.
In this video let's learn how to create and run a task in the background in ASP.NET Core applications. We will learn how to use the BackgroundService class, how to register it to work with the ASP NET Application. We will also see how the IHostedService interface works along with the BackgroundService and also the different Dependency Injection models it supports.
Additional Watching
📹Dependency Injection - • DEPENDENCY INJECTION i...
📹Logging - • LOGGING in ASP.NET Cor...
📹ASP NET Core Series - • ASP.NET Core
Come say hi! ✋
🌍 Blog - rahulpnath.com/
✉ Subscribe to my Newsletter - www.rahulpnath...
🐦Twitter - / rahulpnath
📸Instagram - / rahulpnath
🎥 Recording Setup and Workflow - www.rahulpnath...
Make sure to SUBSCRIBE to the channel. THANK YOU for helping me grow this channel !!
I love the way you just get down to it in your videos. No waffle, but all the detail needed as a jumping off point. Excellent. Thank you.
Awesome! Thank you! Hope you are enjoying the full series bit.ly/asp-net-core-series
Now 23k subscribers, but this channel deserves so much more!
Please smile a bit ...u crossed 5k😃😃. Congratulations
Thank you Shashikant! Once the camera is on I always forget to smile 😀 (But otherwise I do). With time I hope I will get better at this.
Excellent Tutorial Rahul, eagerly waiting for part 2!
Glad you like it Keerthan and thank you for this video suggestion!
Superb ! I been facing this problem lot a time. i was not able to inject scoped and transient dependency into singleton. It's too late to know but finally i got my answer. Keep tuned us.
Glad to hear that
Great content 👍
The simplicity with which ur going in deep about the topic is amazing
Thank you Anurag! Feel free to let know if you have topic suggestions.
Thanks man, I love your explanation because your are not skipping the boundary cases
Glad it was helpful! Hope you are enjoying the full series bit.ly/asp-net-core-series
Simple and very clear tutorial. Thank you for the great information.
Thank you Sachini. Do check out the full series here ruclips.net/p/PL59L9XrzUa-nqfCHIKazYMFRKapPNI4sP
I am sure you will like them too! Do let me know in case you get to watch them 😀
Guys let's encourage this channel, tremendous content ❤❤
Thank you for the love Shanmukh! Hope you are enjoying the series bit.ly/asp-net-core-series
Your presentation style is very simple and to the point. Keep up the good work, Rahul.
Glad you like it. Hope you are enjoying the series bit.ly/asp-net-core-series
I'm new to .net core and this problem held me for two days, can't thank you enough 🙏
Great to hear Atul! The full ASP Series is here, I am sure you will like them bit.ly/asp-net-core-series
@@RahulNath I'm already on it. ⭐⭐⭐⭐⭐
@@atulsingh29 Do drop in if any topic suggestions and feedback 😀👍
I believe this tutorial will help me implement the MS Azure Service Bus Queue as a background service and via IServiceProvider Dependency Injection use repository pattern scoped service to save queue messages to my entityframework SQL Server DB which I will be able to read via my API controller and display to a frontend via API calls using react js. I hope this works...
Yes, It worked.
Thanks...
Glad to hear that! Thank you Efe 😀
Amazing Tutorial Rahul.
Glad you found it useful. The full series is here bit.ly/asp-net-core-series
Excellent presentation by providing first level easy to understand examples, you are my vote !!!
Wow, thank you! Glad you are finding it useful and hope you are liking the series bit.ly/asp-net-core-series
One of my favorite on RUclips.
Thank you Sir for the great explanation.
So nice of you. And you can call me Rahul 😀
Excellent Video!!! Thank you
You are welcome! Hope you are enjoying the series bit.ly/asp-net-core-series
like always, short, simple and usefull
Thank uou Hadi !
Great Lesson Rahul keep doing the same.
Glad you like it - The full series for ASP is here bit.ly/asp-net-core-series
@@RahulNath Could you please explain concurrent collections in C# or send me the link if you have already done the videos.
Thanks
Simple and to the Point! Great Tutorial!
Glad you liked it Sufyan! do check out the full playlist here ruclips.net/p/PL59L9XrzUa-nqfCHIKazYMFRKapPNI4sP
Nice. Thank you. Unit test cases on background services as well next time. Will share nuget packages on which videos could be created. I forgot about that.
Thank you and good idea - will try and add testing too in it.
Great presentation and complete information in one tutorial... great job.
Glad you loved it Niraj! Do check out the full series here bit.ly/asp-net-core-series
Rahul its a great video. I saw each sec enjoying the content
Glad to hear that Hamad. Sure that you will enjoy the full series then bit.ly/asp-net-core-series
Thanks, Rahul; your content is always meaningful and applicable to real solutions. Keep up the great work!! Can you make one with scheduled tasks in background services, please?
Great explanation Rahul👍👍👍
Glad you like it Praveen. Hope you are enjoying the series bit.ly/asp-net-core-series
Such a great content, Rahul!! You're helping me so much with these tutorials. Greetings from Sao Paulo (BR).. cheers
Happy to hear that Douglas! Hope you are enjoying the series bit.ly/asp-net-core-series
Thank you. The content you make is very easy to understand. Hope you will make more videos
Glad you like it. The full ASP series is here ruclips.net/p/PL59L9XrzUa-nqfCHIKazYMFRKapPNI4sP
Hi Rahul,
Amazing video, Can you do a video on reading from database when hosted service starts
Sure happy to - Can you elaborate on your use case, to get some more idea.
Very well explained, can you please make video on logging in asp.net core and generic, non generic collections in asp.net core
Thank you 😀 For logging ruclips.net/video/dxBlBltEDRs/видео.html
Does that help? What specifically are you looking for with collections?
@@RahulNath like how to use non- generic collections in a real world scenario
@@bloopers2967 Mmm that is interesting. I usually don't use that much. What scenario are you using non-generic currently for?
@@RahulNath 😂😂for solving competitive coding questions
@@bloopers2967 Haha ok, one more reason to hate such questions 😂🤣
Thanks a lot! Great content!
Glad you liked it Jack! The full ASP series is here bit.ly/asp-net-core-series
Cảm ơn bạn!
waiting for In Part 2, please give example with some real time examples.
Yes, it's on the list! Thank you for the prompt 😀
Really helpful.... thanks for uploading some great .net contents..easily understandable...waiting for more such content . Thanks Rahul 😊
Thank you Aravind. Do check out the full series here if you haven't already ruclips.net/p/PL59L9XrzUa-nqfCHIKazYMFRKapPNI4sP
Feel free to let know if you have specific topic suggestions.
As usual amazing video Rahul. Thanks for your work and time 😄
Thank you Ivan! These comments make it worth my time, thank you for watching.
Very helpful tutorial. Thank you.
Glad it was helpful Abdul!
Excellent keep it up
Thanks a lot! Hope you are liking the series bit.ly/asp-net-core-series
Good one Rahul, if possible please make video on reading from database when hosted service starts, e.g persistent queue.
But really like your videos
Thats a good suggestion Pratik. I will add that to my list. Glad you like the videos
As usual explained very well Rahul...Thanks a ton bro...👍
Thank you 😀 So happy these help and for letting me know.
Great video and very clear explanation !
Glad you enjoyed it Christian! Do check out the full ASP Series here bit.ly/asp-net-core-series
Thanks for this video
Most welcome Harmeet. Do check out the other videos in this series ruclips.net/p/PL59L9XrzUa-nqfCHIKazYMFRKapPNI4sP
That is an excellent video… really really loved it…thnxx
Glad you liked it! Hope you have checked the full series bit.ly/asp-net-core-series
Always helpful and informative! Get some rest though, I saw the time on your build as 5:02 am! :)
Glad you like it and thank you for the lovely caring comment. I record all my videos during that time (4-5) 😀 (That's when house is least noisy).
Wrote about it here if you are interested. twitter.com/rahulpnath/status/1393813849933897737?s=20
nice Explanation Rahul
Happy you liked it. Do check out the full series here bit.ly/asp-net-core-series
Excellent
Thank you so much 😀Hope you are liking the series bit.ly/asp-net-core-series
Hola buenas
Un vídeo de worker services sería de mucha ayuda
Saludos
Very helpful
Glad it helped - Do check out the full series here bit.ly/asp-net-core-series Hope you like them
Hi Rahul, thanks for your video!!
In scenarios where the application is abruptly closed, does it exists a workaround how to handle those abruptly closings?
It's best to use external queues for critical processing and avoid the background tasks for this as you might loose information. What is your scenario you are using this for?
@@RahulNath what type of external queues do you refer?
Is a hypothetical scenario of thousand of data to process daily, maybe for example financial institution usually process thousands of records to process loans.
I was thinking of batch data split in multiple jobs/tasks ?
@@diegomelgar2696Azure Service Bus Queue, AWS SNS, SQS , Rabbit MQ etc depending on where and how your application is hosted/managed. I have some introduction to this in my Messaging series here ruclips.net/p/PL59L9XrzUa-ku74pfBcy4f3tigwfzGUrG
For critical processing I wouldn't depend on Background Tasks.
@@RahulNath thanks, will check on that!
You are so awesome! Thank you!
You are so welcome! Hope you are enjoying the full series here bit.ly/asp-net-core-series
Good job with the tutorial, could you create some on how to use the QUARTZ library in net core, since the ones that are currently there are very confusing and I think you would make them much easier to understand.
Glad you like the video and Great suggestion! I will add this to my list. I have a blog post from a while back here using Quartz in case it helps www.rahulpnath.com/blog/windows-service-using-topshelf-quartz-and-autofac/
Thank you very helpful.
Glad it was helpful Tobby! Do check out the full series here ruclips.net/p/PL59L9XrzUa-nqfCHIKazYMFRKapPNI4sP
Another great video! I knew about Background service but did not know the limitation you demoed. Thank you for pointing that.
Also, You mentioned that there is a new video coming for exception handling for Background services, can you please add a link for that?.
Glad it was helpful Sachin! Unfortunately I did not get to that video. Are you facing any particular issues? I might look to work on that video soon.
@@RahulNath Not facing any issue as such but curious to see how you will handle it.
@@MrSachintelalwar Have it in my list, yet to get to it 😀
Thank you bro
Glad it helped. Do check out the full series here bit.ly/asp-net-core-series
Hi! I want to save excel files into the local server once every year using scheduler so may i know how to call the excel generating api from my existing controller in my scheduler class
Its a hosted service in WebApp, so if I host that web app in Azure? How will the background task behave? So we duplicate background tasks when we scale web app? So background task should manage some locks to avoid duplication? Any thoughts?
Sorry for delay in getting back. Yes as you scale there will be multiple instances. What problem are you trying to solve using background tasks? Using Azure Functions might be another way if you want to control the number of instances and always want only one instance.
hi Rahul, If I deploy service as window service, and some one stop service on service window when it running, how we get the information of stop time
Hello,What if we want run background service even the application is close?
the background job should be running as long as your web app is up and running. Otherwise I would be looking at Azure Function instead of using a Background Task. Does that help?
Nice Tutorial! I want to build a api that start and stop the background task .how can I do that ?if so,than is it the wise way to start and stop the background task?
You could - Can you provide more details on the use case ?
Hi Rahul, thanks for a another brilliant video. I’m looking for a azure devops ci/cd example for the new Logic Apps Standard. Do you know of a good resource for this? Not looking for entire IaC, rather just continuously build and deploy on commit
Thank you Ershad and happy you like it. Did you find anything interesting on this channel? ruclips.net/user/Azure4Everyone
I haven't worked with Logic Apps much.
@@RahulNath Hi Rahul, the logic app standard sku just recently went GA with MS Build. Previous devops story for logic app
was different. The new logic app standard is running on the azure functions runtime, so it is very similar to app services in terms of ci/cd. But I can’t find a good example as it’s so new.
Serious question. Someone told me that these tasks are utterly unreliable in Azure. Do you have any experience using them in App Services in Azure? Cheers
Yes I've used this in production in Azure App Service and have had no issues. Depends a lot on how they have used/what error handling mechanisms they have in place. Another option for you would be to make it a web job. What is your scenario?
good job man
Glad it helped Ibrahim. Do check out the full series here bit.ly/asp-net-core-series
👍
😀
How do you deploy in IIS?
do you have an example?
I don't have an example for IIS - there are a few on my channel to deploy to Azure Web App bit.ly/azure-devops-series
Good
Why don't you give real life scenerio
Thanks
I want my background service to be run every day at 9AM and run after every 40 minutes till 2PM can you please guide
Suggest looking at WebJobs and using CRON trigger. You could also do this in Background Tasks. Check out libraries like Quartz.net. Hope it helps
could you please make videos on Razor pages and Core Blazor
Thank you Rohan for the suggestion. I have added this to my list. But that will not be coming out immediately. Mostly because I have not explored much of Blazor 😀
I want to run my background task for every 30 seconds throughout the year. For this scenario, can I use this approach? Please advice.
Sure you can - but if the app is down it won't run, so keep that in mind. Might look at Azure Function on a Timer trigger as well depending on the task and how important it is etc.
Hi Rahul, great content! I have a bit of an usage when I fake the scope. It's affecting the IHttpContextAccessor, making it return null. can you help?
Thank you - Do you have a example project that you can send me? hello@rahulpnath.com
Very nice tutorial ☺️ just i have a question that can we run hosted service as per own events. e.g - when task A is completed then we need to fire background service to execute Task B ?
Yes you can use Channels library for this learn.microsoft.com/en-us/dotnet/core/extensions/channels
But depends what kind of tasks and be aware it will be in memory. If you provide more context on the problem I could give some suggestions.
Thank You for reply!!
I have to read an excel having 20k rows and after reading this, we need to execute some business logic for each row.
1. upload an Excel
2. Reading Rows and storing in DB.
3. click on the start process button.
4. Now we will read all the data from the table and perform some tasks (Business logic) in the background for each row (Total around 20k rows).
5. Tech Using .Net Core 3.1
@@shashankpandey1019 I would use messaging for this - so publish a message for each row and process it independently. You can also use background tasks. Once you save the excel records to database signal the background worker using Channels or you can use polling from background job for new jobs/rows in the database. A Message Queue is ideal for these scenarios instead.
Thanks a Lot @RahulNath 😊! It's working for me. I have looked at all your videos. it's an amazing learning. Happy leaning!
#RahulNath, Hi Sir I have developed this task and its running on my machine,But when i publish on IIS Server its showing Swagger page and jobs are not storing and sending into database,I have watched so many solution nothing is working.Please can you help.Lot of setting i have trying.
I have the same problem, can you help us? Rahul Nath #RahulNath @RahulNath
Muy bueno
Gracias!
its wrk in resolving circular reference issue.
Sorry didn't understand?
@@RahulNath want to say i had implemented your solution to resolv circular reference issue in my project , its resolve it.
Great ok - glad it helped!
What if I wanted to repeat a task at the beginning of each month
You could write some custom scheduling but I would choose Web Jobs/Azure Function with a cron trigger. Is that something that works for you?
Where we have register Ihostedservice if in background task create a zip file. Right now we are register it in last of Configureservice
Sorry didn't understand your question. Can you provide more details Shweta?
@@RahulNath is there any order to add Ihostservice in DI container. My backgroud task is converting body to zip file
@@shwetagopi5102 What problem are you facing with the ordering? It shouldn't be a problem with starting the service
How to add multiple cron events inside a single background Service?
Best to use some external packages for that - Have a look at Quartz.net www.quartz-scheduler.net/
Hangfire etc www.hangfire.io/
Or if you can pull them out into serverless functions (Azure Functions, Lambda etc) if you are on cloud. Let me know if that helps.
@@RahulNath Thanks for the suggestion. I will try & let you know.
will that affect the performance of the web api.
Depends on where you are hosting and what you are doing in the Background Tasks. If it's resource heavy you can decouple it to a Function/Lambda (depending on what your hosting platform is).
Is any way to stop the backgroundjob task other than application shutdown? i am eargly waiting for your response
Sorry for the delay. Yes you can exit the loop and run only once or based on your conditions. the first job I show in the example closes down after first execution. If you can give more details on your use case I could suggest something.
@@RahulNath my use case is i created a background service to subscribe a kafka topic. As you said the while loop in the background service exist only when application goes to shutdown. My requirement is to create an endpoint or something that control the start and stop of background task. I don't know it is possible. If its possible please reply.
this method can be used for sending
email automatically for specific user which is inactive user more than 6 month?
Yes you could, but if you are on Azure I might use a Web Job or an Azure Function for that. But that said, you could very well do that in BackgroundTask as well
@@RahulNath thank you sir for your explanation 👍
@@roslanbainal5914 No probs Roslan. And you can call me Rahul 😀
In webforms?
haven't tried yet. Did you get a chance to explore?
this is .net core 3.1 ? how to create in .net 6 bro?
Guessing most of it will be the same - What difficulties are you facing?
Every time I start my web API , the worker doesn't start with it... Of course I added it in program.cs
Hard to tell what might be the reason. Did you try adding a log statement in your background task startup?
@@RahulNath I added logs, breakpoints, database queries. It just won't be executed. The process is running under IIS express (rest API)
@@RahulNath okay, smh it's working now. But not instantly when I start the process but only after I did a first request to the backend over the frontend?! So if I just start my API, the worker won't instantly start. As I log in from the frontend a request will be sent to the API (just casual stuff) and then the worker starts. (After a request)
@@Kasiux Think it should work as soon as app launches. Can you create a minimal sample and send it to me and I can check - Details in the about page.
0:36
?
Can you try to mimic English or US accent? That way it would be less frustrating to listen to your videos and more people would join LOL
Haha, never thought that would be a reason for people not joining. Also can't tell if the people who have joined are because I don't have one. 😀
Excellent
Thank you so much Fahad😀 Make sure to check out the other videos in this series ruclips.net/p/PL59L9XrzUa-nqfCHIKazYMFRKapPNI4sP