How to Run Background Tasks in ASP.NET Core with Hosted Services
By Tan Lee Published on Dec 19, 2024 396
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 Initialize TagHelpers in ASP.NET Core with Shared Data
- Boost Your ASP.NET Core Website Performance with .NET Profiler
- The name 'Session' does not exist in the current context
- Implementing Two-Factor Authentication with Google Authenticator in ASP.NET Core
- How to securely reverse-proxy ASP.NET Core
- How to Retrieve Client IP in ASP.NET Core Behind a Reverse Proxy
- Only one parameter per action may be bound from body in ASP.NET Core
- The request matched multiple endpoints in ASP.NET Core