C
C#17mo ago
Esa

❔ How to handle longrunning tasks and cancellation in asp.net core?

Hi, one of the applications we have at work has a long-running background task. The application is an older fx472 app where we just have a public static Task LongRunningTask; and public static CancellationTokenSource source;, and these are defined in global.asax.cs which i'm now trying to migrate to Startup.cs instead. This task is not dependent on user input and just silently runs every hour. How does one usually handle long-running tasks that may need to be cancelled in asp.net core (.net 7.0)?
7 Replies
Kouhai
Kouhai17mo ago
@Fyren You can use periodic timer with BackgroundService
Esa
Esa17mo ago
So I create a new class that implements IHostedService and use a periodic timer, right? then register that in startup.cs? This service will require access to other scoped services though, can it use DI?
Kouhai
Kouhai17mo ago
Yes, you can implement IHostedService or just inherent BackgroundService And yes, you have access to DI
Esa
Esa17mo ago
okay. Where is the CancellationTokenSource created, is that in startup.cs? Should it be a part of the constructor to the class that implements IHostedService?
Kouhai
Kouhai17mo ago
You can simply call StopAsync on the BackgroundService
Pobiega
Pobiega17mo ago
IHostedServices get cancelled by ASP when a graceful shutdown is requested, so you dont need to manually handle that and, just to be clear, this sounds like an excellent usecase for something like HangFire or Coravel or Quartz - job schedulers
Accord
Accord17mo ago
Was this issue resolved? If so, run /close - otherwise I will mark this as stale and this post will be archived until there is new activity.