Building a Background Worker Service in .NET
When developing applications, there are times when you need to run background processes that execute independently of user interactions. Whether it's automating tasks, handling scheduled operations, or processing data at intervals, .NET Worker Services provide an efficient solution. In this post, we’ll explore what Worker Services are, how they work, and how to implement a simple example that periodically calls an API and saves the data to a local file.
What is a .NET Worker Service?
A Worker Service in .NET is a background application that runs continuously, executing logic in a loop with a specified delay. Unlike web applications or interactive services, Worker Services are designed to operate autonomously, making them ideal for automation scenarios where tasks need to be performed at regular intervals.
Common use cases for Worker Services include:
Setting Up a Worker Service in .NET
To create a Worker Service, follow these steps:
. Create a New Worker Service Project
Open Visual Studio, select Create a new project, and search for Worker Service. Choose the C# Worker Service template and proceed with the default settings. For this example, name the project APICallerService and use .NET 8 (the latest LTS version at the time of writing).
2. Understanding the Worker Class
The core logic of a Worker Service is defined in the Worker.cs file. This class extends BackgroundService, which allows it to run continuously in the background. Let’s break it down:
Here's the default structure of a Worker Service:
public class Worker : BackgroundService
{
private readonly ILogger<Worker> _logger;
public Worker(ILogger<Worker> logger)
{
_logger = logger;
}
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
while (!stoppingToken.IsCancellationRequested)
{
_logger.LogInformation("Worker running at: {time}", DateTimeOffset.Now);
await Task.Delay(1000, stoppingToken);
}
}
}
3. Customizing the Worker Service
For our example, we'll modify the Worker Service to:
领英推荐
Define the API Endpoint
We will use JSONPlaceholder (a free fake API for testing) to fetch To-Do items:
private const string ApiUrl = "https://jsonplaceholder.typicode.com/todos/1";
Implement API Call and File Writing
Modify ExecuteAsync to:
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
using var httpClient = new HttpClient();
const int interval = 5000; // 5 seconds
_logger.LogInformation("Service started at: {time}", DateTimeOffset.Now);
while (!stoppingToken.IsCancellationRequested)
{
try
{
_logger.LogInformation("Contacting API...");
string response = await httpClient.GetStringAsync(ApiUrl, stoppingToken);
string filePath = "data.json";
await File.WriteAllTextAsync(filePath, response, stoppingToken);
_logger.LogInformation("Data saved successfully at {time}", DateTimeOffset.Now);
}
catch (Exception ex)
{
_logger.LogError("Error fetching API data: {error}", ex.Message);
}
await Task.Delay(interval, stoppingToken);
}
}
4. Running the Worker Service
To run the Worker Service, press F5 in Visual Studio. The application will:
Example log output:
[INFO] Service started at 2024-02-25T12:00:00Z
[INFO] Contacting API...
[INFO] Data saved successfully at 2024-02-25T12:00:05Z
Conclusion
Worker Services in .NET offer a simple yet powerful way to run background tasks. In this post, we:
With this foundation, you can extend the Worker Service to include error handling, database integration, or even advanced scheduling.
If you found this guide helpful, subscribe to my YouTube channel for more .NET tutorials!
Founder & CTO
3 周Thanks for sharing!