Building a .NET Worker Service for Background Processing with Message Queues (and Windows Deployment)

Table of contents
- โ Why Use a .NET Worker Service?
- ๐ Building a .NET Worker Service That Listens to a Message Queue โ Step-by-Step Guide + Windows Deployment
- โ Step 1: Create a New Worker Service Project
- โ Step 2: Add Your Messaging Queue Library
- โ Step 3: Implement Queue Listener Logic
- โ Step 4: Enable Windows Service Integration
- โ Step 5: Publish the Worker
- โ Step 6: Create the Windows Service
- โ Optional: Log Output
- โ Final Checklist
- ๐ Conclusion

โ Why Use a .NET Worker Service?
.NET Worker Services are a powerful way to run background tasks reliably and efficiently. Here are some key benefits:
๐ 1. Continuous Background Execution
Worker Services are designed to run indefinitely, making them ideal for:
Queue listeners
Scheduled jobs
Long-running background tasks
They provide a stable environment for work that needs to happen behind the scenes.
๐ 2. Seamless Integration with Hosting Models
You can easily run a Worker Service:
As a Windows Service
As a Linux daemon
Inside a Docker container
On cloud platforms (e.g., Azure App Service or Kubernetes)
This flexibility allows you to deploy them in various environments without code changes.
๐งฑ 3. Built on .NET Generic Host
Worker Services use the same dependency injection, configuration, and logging infrastructure as ASP.NET Core applications. This means:
Easy setup and maintenance
Familiar patterns for .NET developers
Built-in support for structured logging and metrics
โ๏ธ 4. Perfect for Message-Driven Systems
When paired with a message queue, Worker Services shine. They help:
Decouple producers and consumers
Handle workloads asynchronously
Improve performance and reliability
๐ก๏ธ 5. Reliable and Recoverable
As a Windows Service, your worker can:
Start automatically on boot
Restart on failure
Run without user interaction
This makes it ideal for production workloads that require resilience.
๐ Building a .NET Worker Service That Listens to a Message Queue โ Step-by-Step Guide + Windows Deployment
When building distributed systems or background processing pipelines, message queues and worker services play a vital role. In this blog, Iโll show you how to create a .NET Worker Service that listens to a message queue, processes messages in the background, and runs continuouslyโeven after rebootsโby registering it as a Windows Service.
Letโs walk through this with clean steps and code examples! ๐ก
๐ ๏ธ Tech Stack:
.NET 8 (or .NET 6/7)
Any message queue system (abstracted)
Windows (for deployment)
Visual Studio / VS Code
โ Step 1: Create a New Worker Service Project
dotnet new worker -n MessageQueueWorker
cd MessageQueueWorker
This creates a project with a hosted background service.
โ Step 2: Add Your Messaging Queue Library
Install the appropriate NuGet package for your message broker:
dotnet add package Your.MessageQueue.Client
Replace this with your actual queue library.
โ Step 3: Implement Queue Listener Logic
In Worker.cs
, write code to connect to the message queue and consume messages:
public class Worker : BackgroundService
{
private readonly ILogger<Worker> _logger;
private IMessageQueueConnection _connection;
private IMessageQueueConsumer _consumer;
public Worker(ILogger<Worker> logger)
{
_logger = logger;
InitializeQueue();
}
private void InitializeQueue()
{
// Replace with actual implementation
_connection = MessageQueueFactory.CreateConnection("localhost");
_consumer = _connection.CreateConsumer("my-queue");
_consumer.OnMessageReceived += (sender, message) =>
{
var content = Encoding.UTF8.GetString(message.Body);
_logger.LogInformation($"Received message: {content}");
};
}
protected override Task ExecuteAsync(CancellationToken stoppingToken)
{
_consumer.StartListening();
return Task.CompletedTask;
}
public override void Dispose()
{
_consumer?.Dispose();
_connection?.Dispose();
base.Dispose();
}
}
โ Step 4: Enable Windows Service Integration
Open Program.cs
and modify the builder to enable Windows service hosting:
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
Host.CreateDefaultBuilder(args)
.UseWindowsService() // This line makes it run as a Windows Service
.ConfigureServices((hostContext, services) =>
{
services.AddHostedService<Worker>();
})
.Build()
.Run();
โ Step 5: Publish the Worker
Publish the project as a folder deployment:
dotnet publish -c Release -o C:\Services\MessageQueueWorker
This generates the files required to run the service.
โ Step 6: Create the Windows Service
Use PowerShell (as Administrator) to register the Windows Service:
New-Service -Name "MessageQueueWorker" `
-BinaryPathName "C:\Services\MessageQueueWorker\MessageQueueWorker.exe" `
-DisplayName "Message Queue Worker Service" `
-Description "Processes background jobs from a messaging queue." `
-StartupType Automatic
Then start the service:
Start-Service -Name "MessageQueueWorker"
โ You can now verify it in Services.msc.
โ Optional: Log Output
Add logging to a file by modifying appsettings.json
:
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft": "Warning"
}
}
}
You can also integrate with Windows Event Logs or structured logging tools (e.g., Serilog, NLog) for production setups.
โ Final Checklist
Worker Service Project: Ensure the Worker Service is set up correctly with message queue integration.
Message Queue Configured: Verify that your message queue (e.g., RabbitMQ, Azure Service Bus, etc.) is set up and running.
Windows Service Registration: Double-check that the Worker Service is registered as a Windows Service.
Task Execution: Confirm that the worker listens to the queue and processes tasks as expected.
Logging & Monitoring: Set up logging and monitoring to keep track of background task execution.
Test Locally: Ensure the Worker Service runs as expected in your local environment before deploying.
Deploy: Publish your Worker Service and deploy it to your production environment.
๐ Conclusion
Congrats! You now have a fully functioning .NET Worker Service listening to a message queue and running as a Windows Service. This pattern can be extended to:
Task scheduling and background processing
Asynchronous data syncing
Event-driven architecture
Scalable job queues
If you found this guide helpful, leave a like โค๏ธ or share it! Let me know your thoughts or questions in the comments!
Subscribe to my newsletter
Read articles from Pranali Kulkarni directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
