/
The Background on  Background Tasks in .NET Core The Background on  Background Tasks in .NET Core

The Background on Background Tasks in .NET Core - PowerPoint Presentation

reagan
reagan . @reagan
Follow
69 views
Uploaded On 2024-01-03

The Background on Background Tasks in .NET Core - PPT Presentation

Slides up at scottsaubercom scottsauber Audience NET Core Developers In need of running a background task scottsauber Agenda What are background tasksjobs What type of problems are suitable for a background taskjob ID: 1038019

background net core app net background app core scottsauber backgroundservice work host asp job hangfire ihostedservice tasks cookie running

Share:

Link:

Embed:

Download Presentation from below link

Download Presentation The PPT/PDF document "The Background on Background Tasks in ...." is the property of its rightful owner. Permission is granted to download and print the materials on this web site for personal, non-commercial use only, and to display it on your personal computer provided you do not modify the materials and that you retain all copyright notices contained in the materials. By downloading content from our website, you accept the terms of this agreement.


Presentation Transcript

1. The Background on Background Tasks in .NET CoreSlides up at scottsauber.comscottsauber

2. Audience.NET Core DevelopersIn need of running a background taskscottsauber

3. AgendaWhat are background tasks/jobs?What type of problems are suitable for a background task/job?What options are out there?IHostedServiceBackgroundServiceWorker ServiceHangfireWhy would I choose one over the other?Deep dive into eachDemosQuestionsscottsauber

4. GoalKnow all your options for running background tasksWhy choose one over anotherscottsauber

5. Who am I? Software ConsultantCo-organizer of Iowa .NET User Group Friend of RedgateBlog at scottsauber.comscottsauber

6. What problem do background tasks solve?Cron jobsProcess messages from a queue every X minutesClean up database or file system every X minutesSend email notification every X minutes under certain circumstancesRefresh cache every X minutesCheck for updates to database every X minutes and push updates via SignalRPerform some CPU intensive work asynchronouslyRe-train ML datasetsscottsauber

7. OptionsIHostedServiceBackgroundServiceWorkerServiceHangfireCloud optionsscottsauber

8. These options are kind of like baking cookies

9. IHostedService“Make Your Own Recipe”(Cookie Jar Included)

10. What is an IHostedService?Lets you host a background job inside an ASP.NET Core AppASP.NET Core app is your cookie jarInterface with StartAsync and StopAsyncRaw, fundamental building block for other optionsRegister via dependency injection and services.AddHostedService<T>scottsauber

11. Demo

12. How does an IHostedService work?Register with DIStopAsync’s cancellation token has 5 seconds to shutdown gracefullyStopAsync might not be called if the app shuts down unexpectedlyscottsauber

13. How does an IHostedService work?scottsauberImage Credit: Andrew Lock

14. How does an IHostedService work?StartAsync blocks the rest of your app from startingPush blocking long-running work out of StartAsync This goes for BackgroundService laterUNLESS, you truly don’t want your app to boot until this finishesi.e. Database Migrationsscottsauber

15. When do I use IHostedService?You will implicitly use it with BackgroundService and Worker ServicesYou need full control over Starting and StoppingAND will not use the base BackgroundService implementationscottsauber

16. When do I NOT use IHostedService?Should be using BackgroundService or WorkerService 95%+ of the timeOther reasons will be the same as BackgroundService (next)scottsauber

17. BackgroundService“Follow The Recipe”(Cookie Jar Included)

18. What is a BackgroundService?Lets you host a background job inside an ASP.NET Core AppASP.NET Core app is your cookie jarAbstract class, implements IHostedServiceExposes ExecuteAsync abstract methodHandles Starting and Stoppingscottsauber

19. Demo

20. How does a BackgroundService work?Register with DIExposes ExecuteAsync abstract methodCan still override StartAsync and StopAsyncscottsauber

21. scottsauber

22. When do I use BackgroundService?Need a simple background task runner Either as part of your ASP.NET Core application or by itselfLess gotchas than IHostedServiceCan’t accidentally prevent app from booting unless override StartAsyncHandles cancellationsWant an ASP.NET Core endpoint to health check your background taskInstead of WorkerServicesscottsauber

23. When do I NOT use BackgroundService?Too much co-location with your app/API can get unruly and outweigh the convenience of co-locationIt DependsScaling out can be a problem if your code isn’t idempotentFix by making code idempotent or not allowing scale outscottsauber

24. WorkerService“Follow The Recipe”(BYO Cookie Jar)

25. What is a WorkerService?Enhanced .NET Core Console App templatedotnet new worker –o my-custom-workerAllows you to have an IHostConfiguration, Dependency Injection, Logging, etc.Registers a Worker class as a HostedServiceDoes not take an opinion on how to host console appNo cookie jarConsole app called from schedulerWindows Servicesystemdscottsauber

26. Demo

27. How does a WorkerService work?Project Sdk of Microsoft.NET.Sdk.WorkerPackageReference to Microsoft.Extensions.Hostingscottsauber

28. How do I host WorkerServices?Scheduler calls Console AppWindows Scheduled Tasks, k8s cron jobs, Azure Logic Apps, AWS Scheduled Tasks, GCP Cloud SchedulerWindows Service or Systemd (Windows or Linux)scottsauber

29. When do I use WorkerServices?Want an out-of-proc way of running background tasksPrefer hosting background services outside of a web appAvoid app pool recyclesNatural migration for a full .NET framework Windows Servicescottsauber

30. When do I NOT use WorkerServices?Prefer deploying as a web appWant to co-locate with existing web app/APIWant a healthcheck endpointscottsauber

31. Hangfire“Buy pre-packaged cookies”

32. What is Hangfire?Full featured library for running jobs in ASP.NET CoreFree for commercial use but paid if you want support ($500-$4500/yr)Comes with UI for monitoring and historySupports Cron and ad-hoc running of jobsAllows for continuationsAutomatic retriesSupports concurrency limitingPersists job state to databasescottsauber

33. Demo

34. How does Hangfire work?Serializes method call and all argumentsCreates background job based on that informationSaves job to persistent storageStarts background job if immediatescottsauber

35. When do I use Hangfire?Want to host jobs in ASP.NET CoreNeed features Hangfire offersDon’t want to write plumbing codeOk with relying on a 3rd party libraryscottsauber

36. When do I NOT use Hangfire?Do not want to host jobs in ASP.NET CoreHave basic needs and do not need Hangfire’s featuresDo not want to rely on 3rd party libraryscottsauber

37. Cloud optionsAzure FunctionsAzure WebJobsAWS LambdasGCP Cloud Scheduler + Cloud FunctionsDidn’t cover these to avoid cloud specificscottsauber

38. TakeawaysAwareness to all the options available to youMore information to make the best decision for you and your companyscottsauber

39. Resourceshttps://docs.microsoft.com/en-us/aspnet/core/fundamentals/host/hosted-services?view=aspnetcore-3.1&tabs=visual-studiohttps://docs.microsoft.com/en-us/dotnet/architecture/microservices/multi-container-microservice-net-applications/background-tasks-with-ihostedservicehttps://www.hangfire.io/ https://app.pluralsight.com/library/courses/building-aspnet-core-hosted-services-net-core-worker-services/scottsauber

40. Questions?scottsauberSlides up at scottsauber.com

41. Thanks!scottsauberSlides up at scottsauber.com