DEV Community

Cover image for Building a Background Worker Service in .NET
Nick Proud
Nick Proud

Posted on

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:

  • Background data processing
  • Automated API polling
  • Scheduled task execution
  • System monitoring and logging

Setting Up a Worker Service in .NET

To create a Worker Service, follow these steps:

1. 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:

  • The ExecuteAsync method contains a while loop that runs indefinitely unless a cancellation request is received.
  • The loop includes a delay (Task.Delay), defining how often the logic should run.
  • Logging is used to output messages indicating the execution state.

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);
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

3. Customizing the Worker Service

For our example, we'll modify the Worker Service to:

  1. Call an API every 5 seconds.
  2. Save the response to a local file.
  3. Log each API request and response.

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";
Enter fullscreen mode Exit fullscreen mode

Implement API Call and File Writing

Modify ExecuteAsync to:

  • Fetch data from the API using HttpClient.
  • Write the JSON response to a local file.
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);
    }
}
Enter fullscreen mode Exit fullscreen mode

4. Running the Worker Service

To run the Worker Service, press F5 in Visual Studio. The application will:

  • Log messages to indicate execution progress.
  • Fetch data from the API every 5 seconds.
  • Save the data to data.json.

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
Enter fullscreen mode Exit fullscreen mode

Conclusion

Worker Services in .NET offer a simple yet powerful way to run background tasks. In this post, we:

  • Introduced Worker Services and their use cases.
  • Created a Worker Service in .NET.
  • Implemented an API polling mechanism with logging and file storage.

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!

Top comments (0)