How to Run Background Tasks in ASP.NET Core with Hosted Services
By FoxLearn 12/19/2024 9:52:02 AM 35
Background tasks are particularly useful in microservices architectures, where you often need to implement a messaging service like RabbitMQ to listen for and consume messages from a message queue.
Start by creating a new ASP.NET Core web application, then create a new class named HelloWorldHostedService
.
This class will implement the IHostedService
interface.
public class HelloWorldHostedService : IHostedService { private Timer _timer; // Run the logic when the service starts public Task StartAsync(CancellationToken cancellationToken) { // Register the background task using a timer RegisterTimerTask(); return Task.CompletedTask; } public Task StopAsync(CancellationToken cancellationToken) { Debug.WriteLine("Stopping task..."); return Task.CompletedTask; } private void RegisterTimerTask() { // Call HelloWorld every 5 seconds in the background _timer = new Timer(HelloWorld, null, 0, 5000); } void HelloWorld(object state) { Debug.WriteLine($"{DateTime.Now}"); Debug.WriteLine("Hello World!"); Debug.WriteLine("This is a hosted service"); } }
The IHostedService
interface requires you to implement StartAsync()
and StopAsync()
methods. In our example, we use a timer to invoke the HelloWorld()
method every 5 seconds.
- In the
StartAsync()
method, we register the timer by calling theRegisterTimerTask()
method. - In the
StopAsync()
method, we simply log a message when the service stops.
Now, open your Startup.cs
file and register the hosted service:
// Register the hosted service services.AddHostedService<HelloWorldHostedService>();
Run your application.
You should see the background task running in the Output window of Visual Studio, printing the "Hello World" message every 5 seconds.
Alternatively, you can use the BackgroundService
class, which is a simplified base class for running background tasks in ASP.NET Core.
public class HelloWorldBackgroundService : BackgroundService { protected async override Task ExecuteAsync(CancellationToken stoppingToken) { while (!stoppingToken.IsCancellationRequested) { Debug.WriteLine("Background service running!! Hello!"); await Task.Delay(8000, stoppingToken); } } }
Similar to the previous approach, you need to register the background service in your Startup.cs
file:
// Register the background service services.AddHostedService<HelloWorldBackgroundService>();
That's all there is to creating a simple background task in an ASP.NET Core application. Whether you use IHostedService
or BackgroundService
, the process is straightforward:
- Create a class that implements
IHostedService
orBackgroundService
. - Implement the logic for the background task.
- Register the service in your
Startup.cs
file.
- How to use CORS in ASP.NET Core
- How to Send Emails in ASP.NET Core
- Implementing Scheduled Background Tasks in ASP.NET Core with IHostedService
- Creating an Web API in ASP.NET Core
- 8 Essential Tips to Protect Your ASP.NET Core Application from Cyber Threats
- Implementing Caching in ASP.NET Core
- Building a Custom Request Pipeline with ASP.NET Core Middleware
- How to fix 'Authorization in ASP.NET Core' with 401 Unauthorized