.NET 6 — Worker Service

Levent Ozturk
3 min readMay 22, 2023

--

Hi,

In today’s article, I want to introduce you to the Worker Service feature that came with .NET 6 and briefly explain what you can do. Let’s get started!

With the release of .NET 6, Microsoft introduced the Worker Service feature, which offers a lightweight and efficient way to build long-running background services. In this article, we will dive into the capabilities and usage of Worker Service, highlighting its advantages over traditional Windows Services. We will explore the key concepts, methods, and scenarios where Worker Service shines to illustrate its usage.

Worker Service and Its Use Cases

Worker Service is a versatile tool suitable for various scenarios where you need to perform background tasks or process data continuously. Let’s look at a few common use cases:

  • Real-time data processing
  • Periodic tasks
  • Message processing

Differences Between Worker Service and Windows Service

Worker Service brings significant improvements over traditional Windows Services, such as:

Simplicity and lightweight: Worker Service simplifies the development and deployment process by providing a more lightweight and modern framework.

Cross-platform support: Worker Service works seamlessly on Windows, Linux, and macOS, making it an ideal choice for multi-platform development. You can write your Worker Service once and run it on various operating systems.

Methods and Usage Patterns

Worker Service follows a pattern where the execution logic is written within a background worker class inheriting from the BackgroundService base class. Let's explore the methods:

  • ExecuteAsync: This method contains the main execution logic of the Worker Service. It is an asynchronus method where you can write the code for processing tasks.
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
while (!stoppingToken.IsCancellationRequested)
{
// Perform background tasks here
await Task.Delay(1000, stoppingToken);
}
}
  • StartAsync and StopAsync: These methods handle the service startup and gently shutdown, allowing you to perform any necessary intialization or cleanup operations.
public override Task StartAsync(CancellationToken cancellationToken)
{
// Connect to the database or
DbContext.Connect();
// Initialize message queues and set up connections
MessageQueueManager.Initialize();

return base.StartAsync(cancellationToken);
}

public override Task StopAsync(CancellationToken cancellationToken)
{
// Close the database connection
DbContext.Disconnect();
// Release resources and stop message queues
MessageQueueManager.ReleaseResources();

return base.StopAsync(cancellationToken);
}

Using Dependency Injection

The lifetime of Worker Service is set as Singleton. Therefore, if you register a Transient or Scoped service to this service, you will get an error. There is a Microsoft article for you to solve this error.

To summarize briefly, an instance is obtained in the IServiceScope object using the “using block” and the instance of the requested service is obtained using theGetRequiredService() method. Like this:

using IServiceScope scope = _serviceProvider.CreateScope();
IExampleService exampleService = scope.ServiceProvider.GetRequiredService<IExampleService>();

var serviceResponse = await exampleService.ExampleMethodAsync();

Handling Errors

Try-catch block can be used to catch and log errors. You can take action against all errors you may encounter by using an exception middleware for errors you will receive in the services you call in Worker Service.

Integration with Quartz Library

You can integrate Worker Service with the Quartz library for advanced job scheduling capabilities, including running jobs at specific times of the day. Here is an example of using Quartz within a worker service for such a scenario:

public async Task StartAsync(CancellationToken cancellationToken)
{
IScheduler scheduler = await _schedulerFactory.GetScheduler(cancellationToken);

IJobDetail job = JobBuilder.Create<MyScheduledJob>()
.WithIdentity("MyJob", "MyGroup")
.Build();

ITrigger trigger = TriggerBuilder.Create()
.WithIdentity("MyTrigger", "MyGroup")
.WithCronSchedule("0 0 9,17 * * ?") // 9 AM and 5 PM every day
.Build();

await scheduler.ScheduleJob(job, trigger, cancellationToken);
await scheduler.Start(cancellationToken);
}

You can check the Cron Triggers page of the Quartz library to learn more about these schedules.

That’s all I have to say in this article. What you can do with worker service can vary a lot depending on your needs and imagination. Ijust wanted to help you open this door. Thank you for reading.

--

--