❔ 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
@Fyren You can use periodic timer with
BackgroundService
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?
Yes, you can implement
IHostedService
or just inherent BackgroundService
And yes, you have access to DIokay. Where is the CancellationTokenSource created, is that in startup.cs? Should it be a part of the constructor to the class that implements IHostedService?
You can simply call StopAsync on the
BackgroundService
IHostedService
s 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 schedulersWas 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.