Skip to content
  • Home
  • About
  • No Access
  • Privacy Policy
Bits of .NET
Bits of .NET
  • Asp.Net Core
  • C#
  • SQL
  • JavaScript
  • CSS
  • About
  • ErcanOPAK.com
  • No Access
  • Privacy Policy

Bits of .NET

Daily micro-tips for C#, SQL, performance, and scalable backend engineering.

  • Asp.Net Core
  • C#
  • SQL
  • JavaScript
  • CSS
  • About
  • ErcanOPAK.com
  • No Access
  • Privacy Policy
Asp.Net Core

.NET Core: Build Background Tasks with Worker Services

- 12.07.26 - ErcanOPAK

⚙️ Worker Services = Background Tasks

Apps need background tasks. Worker Services run in background. Scheduling, queues, monitoring.

📝 Worker Setup

# Create Worker Project
dotnet new worker -n MyWorker
cd MyWorker

# Program.cs
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;

var host = Host.CreateDefaultBuilder(args)
    .ConfigureServices(services =>
    {
        services.AddHostedService();
        services.AddScoped();
    })
    .Build();

await host.RunAsync();

# Worker Service
public class Worker : BackgroundService
{
    private readonly ILogger _logger;
    private readonly IServiceProvider _serviceProvider;

    public Worker(ILogger logger, IServiceProvider serviceProvider)
    {
        _logger = logger;
        _serviceProvider = serviceProvider;
    }

    protected override async Task ExecuteAsync(CancellationToken stoppingToken)
    {
        while (!stoppingToken.IsCancellationRequested)
        {
            _logger.LogInformation("Worker running at: {time}", DateTimeOffset.Now);
            
            using var scope = _serviceProvider.CreateScope();
            var service = scope.ServiceProvider.GetRequiredService();
            await service.DoWorkAsync();
            
            await Task.Delay(1000, stoppingToken);
        }
    }
}

🎯 Advanced Workers

// Timer-based worker
public class TimedWorker : BackgroundService
{
    private readonly ILogger _logger;
    private readonly PeriodicTimer _timer = new(TimeSpan.FromSeconds(30));

    protected override async Task ExecuteAsync(CancellationToken stoppingToken)
    {
        while (await _timer.WaitForNextTickAsync(stoppingToken))
        {
            _logger.LogInformation("Timed task executed at {time}", DateTime.Now);
        }
    }
}

// Queue worker
public class QueueWorker : BackgroundService
{
    private readonly ILogger _logger;
    private readonly IBackgroundQueue _queue;

    protected override async Task ExecuteAsync(CancellationToken stoppingToken)
    {
        while (!stoppingToken.IsCancellationRequested)
        {
            var workItem = await _queue.DequeueAsync(stoppingToken);
            await ProcessItemAsync(workItem);
        }
    }
}

// Multiple workers
services.AddHostedService();
services.AddHostedService();
services.AddHostedService();

// Run as Windows Service
dotnet add package Microsoft.Extensions.Hosting.WindowsServices
builder.UseWindowsService();

// Run as Linux Service
builder.UseSystemd();

💡 Worker Tips

  • Use for background jobs
  • Handle cancellation properly
  • Use DI for services
  • Log errors and status
  • Use for long-running tasks

“Worker Services run background tasks. Scheduling, queues, monitoring. Essential for background processing.”

— .NET Developer

Related posts:

.NET Core: Background Services with IHostedService

.NET Core: Background Services with IHostedService

ASP.NET Core Rate Limiting: Protect Your API from DDoS and Abuse

ASP.NET Core Rate Limiting: Protect Your API from DDoS and Abuse

.NET Core: Use ILogger with Scopes for Better Log Context

.NET Core: Use ILogger with Scopes for Better Log Context

Views: 7

Post navigation

Git: Use Submodules for External Repositories
SQL: Use Indexing for Query Performance

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

November 2026
M T W T F S S
 1
2345678
9101112131415
16171819202122
23242526272829
30  
« Oct    

Most Viewed Posts

  • How to make theater mode the default for Youtube (1,068)
  • Get the User Name and Domain Name from an Email Address in SQL (990)
  • How to add default value for Entity Framework migrations for DateTime and Bool (986)
  • Get the First and Last Word from a String or Sentence in SQL (865)
  • How to select distinct rows in a datatable in C# (859)
  • How to enable, disable and check if Service Broker is enabled on a database in SQL Server (661)
  • Add Constraint to SQL Table to ensure email contains @ (619)
  • Average of all values in a column that are not zero in SQL (577)
  • How to use Map Mode for Vertical Scroll Mode in Visual Studio (553)
  • Find numbers with more than two decimal places in SQL (481)

Recent Posts

  • Network Speed Monitor Windows Application v2.5.1
  • Ağ Hızı İzleyici Windows Uygulaması v2.5.1
  • How to make theater mode the default for Youtube
  • The AI Prompt That Audits a Function for Thread-Safety Gaps
  • Ajax: Fix a Fetch Request Caching a Response Despite No-Store
  • WordPress: Fix a Navigation Block Losing Submenu Items After Sync
  • Visual Studio: Fix CodeLens Reference Counts Stuck at Stale Numbers
  • C#: Fix a UTF-8 String Literal Behaving Differently in a Switch
  • Photoshop: Fix a Liquify Mesh Snapping Back on a Smart Object
  • The AI Prompt That Turns a Crash Dump Into a Short Repro Script

Most Viewed Posts

  • How to make theater mode the default for Youtube (1,068)
  • Get the User Name and Domain Name from an Email Address in SQL (990)
  • How to add default value for Entity Framework migrations for DateTime and Bool (986)
  • Get the First and Last Word from a String or Sentence in SQL (865)
  • How to select distinct rows in a datatable in C# (859)

Recent Posts

  • Network Speed Monitor Windows Application v2.5.1
  • Ağ Hızı İzleyici Windows Uygulaması v2.5.1
  • How to make theater mode the default for Youtube
  • The AI Prompt That Audits a Function for Thread-Safety Gaps
  • Ajax: Fix a Fetch Request Caching a Response Despite No-Store

Social

  • ErcanOPAK.com
  • GoodReads
  • LetterBoxD
  • Linkedin
  • The Blog
  • Twitter
© 2026 Bits of .NET | Built with Xblog Plus free WordPress theme by wpthemespace.com